Problems with inheritance in the STL [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
In http://www.stepanovpapers.com/notes.pdf, Alexander Stepanov mentions:
It is interesting to note that the only examples of inheritance that
remained in STL inherit from empty classes. Originally, there were
many uses of inheritance inside the containers and even iterators, but
they had to be removed because of the problems they caused.
What are the technical problems that precluded the use of inheritance in the STL?

I think I will put some comments directly from Alexander Stepanov (http://www.stlport.org/resources/StepanovUSA.html).
Question:
STL is full of creative uses of templates, such as symbolic
types exported from classes, or the pattern matching of a set of
overloaded algorithms onto iterator tags. Surely enough, no standard
C++ Programming book speaks about those idioms. How did you come to
these C++ code idioms?
Answer:
I knew exactly what I was trying to accomplish. So I tweaked
the language until I was able to get by. But it took me many years to
discover all the techniques. And I had many false starts. For example,
I spent years trying to find some use for inheritance and virtuals,
before I understood why that mechanism was fundamentally flawed and
should not be used. I am very happy that nobody could see all the
intermediate steps - most of them were very silly. It takes me years
to come up with anything half decent. It also helped that Bjarne was
willing to put certain features in the language just to enable some of
my idioms. He once refered to it as "just in time language design."
Next, I will allow myself to direct you to this great answer:
https://stackoverflow.com/a/1039904/210971
OOP is not the holy grail. It's a cute idea, and it was quite an
improvement over procedural languages back in the 70's when it was
invented. But it's honestly not all it's cracked up to be. In many
cases it is clumsy and verbose and it doesn't really promote reusable
code or modularity.
That is why the C++ community is today far more interested in generic
programming, and why everyone are finally starting to realize that
functional programming is quite clever as well. OOP on its own just
isn't a pretty sight.
And now something from me:
OOP rules dictates the way (inheritance, polymorphism, etc.) a programmer thinks about interaction between things (objects, entities, tribbles, etc.).
This is clearly visible in this simple Java example from time before adding support for generics (but these are not as verbose as in C++).
List v = new ArrayList();
v.add("test");
Integer i = (Integer)v.get(0); // Run time error
Although the code is compiled without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.
List<String> v = new ArrayList<>();
v.add("test");
Integer i = v.get(0); // (type error) compilation-time error
Alexander Stepanov recognized that generic approach can solve this issue, help in providing logical separation (abstraction) between data structures and algorithms. This is why there is so much emphasis on iterators, functors, and many other idioms that fit very well into generic world.

Related

Allow ONLY c++ 11 coding features and style [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Is there a way to enforce the use of modern c++ 11 features from the compiler?
We have to start a new project and stay in C++ will benefit us from the use of the our existing tools and libraries, but what is currently hurting us to the death is the abuse of C style coding, raw pointers, C style vectors and all the dangerous C features that are so error prone or produce errors that are really hard to track, you know what i mean.
I read a note about what is bad in C++ today (c++11 and beyond) is the c++ past and the abuse of low level/old features when is not necessary.
I really would like to enforce from the compiler or with other tool the use of c++ 11 features like smart pointers, containers, reference parameters, c++ standard library and not C libraries, etc.
Thank you very much.
EDIT: I thought it is not necessary to clarify the use of code review. etc. I just ask if there is or not a tool/mechanism that filters creating features, or enforce modern safer features/coding practices. All the lose ends we will manage or figure out later. Thank you very much!
You might want to take a look at clang-modernize, it can help with some of what you're looking for. In addition running static analysis to help catch bad practices could help identify areas of your codebase in particular need of some attention / modernization. There are a number of such tools associated with clang and MSVC also has its own static analysis if you're working with Visual Studio.
The only way to ensure c++11 features like auto variable declarations, using lambda definitions, range based for loops, etc. are used preferred to older techniques are human based code reviews.
Usage of deprecated stuff, like usage of std::auto_ptr may be sorted out by warnings already.
But enforcing new way styles might become hard, without having a 2nd pair of experienced eyes looking at the code.
I could think of instrumenting an appropriate static code analysis tool, to detect old style patterns and propose the c++11 standard way to do it, but that's a way too broad topic, and depends on the static analysis tool used.
At the risk of getting downvoted to oblvion.
So you or your "expert" on C++ programming, want to ban certain practices.
Because you know they are bad.
One such practice is using raw pointers. Shame that there are C++ programmers who not only use pointers very often, but think they are a good thing thing to use. Guys like Herb Sutter, who in a recent talk ( CppCon I think ) said exactly that.
Another practice you mention is using C style vectors. Not a problem since C does not have vectors.
Those are really the only two that you mention. But you do talk about banning features that cause errors. That can easily be achieved. Instead of issuing your programmers computers. Issue them etch-a sketch's.
Other then that, I would say that your company should hire people who are real experts, not some guy who read a Herb Schildt book.
PS: I was trying to remember what your post smelled like, now I remember. It smells like one of those deign doc review, where one guy spend half the time arguing about spelling errors in the design docs.

implementing neural networks using c vs using c++? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm imlementing Neural Networks using C language for a class. I haven't programmed with C++ nor with C for a long time. I started my first couple implementations using C language and it was a pain in the neck!
Now, I am not sure is it because of the language or its how NN is with any language??
BTW, we are not allowed to use any NN toolbox or libraries.
Some people told me its much easier to do it in C++. But I am in a very tight schedule and I'm afraid I might waste "valuable" time transitioning to C++ to find out the benefit is marginal!
So I thought you might guide me into this? Will it be worth it (time efficiency wise) to switch to C++ or not?
Thanks
Just like any other programming task (that doesn't rely on some framework which is only available in 1 language), there is no magical advantage gained by using a special language for Neural Networks.
If you agree that writing code in C++ in general is much easier than writing code in C, then writing Neural Networks code in C++ is much easier than writing Neural Networks code in C. But that is a highly opinion based topic.
Transitioning to C++ could be worth your time, especially if you've already developed some Object Oriented skills and understanding (even if not with the C++ language itself). However if OO is difficult for you, then the transition may cause more harm than good. It depends on you as a programmer.
The transition won't be as hard as you think. In my opinion, it's less like learning a new language altogether, but instead more like learning new features to a language. Keep in mind that all C code you write will still compile in C++ (mostly, I think? See Kitsune's comment on this answer) because C++ is almost a superset of C.
There's no... direct benefit, so to speak. You can still solve the problem in C, but C++ and Object Orientation may help you create a better, more sharable and understandable solution as although I don't know so much about Nueral Networks, I'm pretty sure some of the characteristics can be neatly abstracted thanks to Object Orientation.
Then again, if OO isn't your peice of cake, then this may end up making it even harder for you. Consider your strengths as a programmer: could you draw a class diagram to figure out how everything fits together comfortably? Do you have a good understanding and appreciation of OO concepts like interfacing and abstraction? If not, then OO could do more harm than good.

thinking objectively vs. functionally [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
As I try to increase my knowledge of functional programming, I'm finding it quite difficult to re-imagine the solutions to problems I've solved in an OOP language in terms of functions, particularly where widgets are involved. Sites like Project Euler and 4Clojure are great for learning core functions and techniques for manipulating primitive data, but what I'd really like is a resource that discusses how to idiomatically translate OOP constructs into FP, with particular attention to identifying when and how to use state. (To use a concrete example, what is the best way to implement a piano keyboard in Clojure?)
what I'd really like is a resource that discusses how to idiomatically translate OOP constructs into FP
Don't. That's a classic XY problem.
I hate analogies but an equivalent in engineering might be to say that you've mastered metalwork and want to learn plastics by recreating the same shapes in plastic. In reality, you never want to translate what you know into what you're learning. What you really want to do is learn how to solve familiar problems using new techniques. Going back to engineering, good plastic designs are not the same shape as good metal designs. In terms of programming, solutions build using one paradigm never translate well to another. You should re-solve the problems from scratch.
I know two books that might help:
"Functional Programming for the Object-Oriented Programmer" by Brian Marick.
"Clojure Programming" by Chas Emerick, Brian Carper and Chirstophe Grand. Chapter 12 is about how to "translate" Object-Oriented Design Patterns to Clojure.
I'm not aware of any book that will teach us how to translate OOP constructs into Functional ones. Just give yourself some time and you will grasp the functional idioms.
Don't try to map between OOP code and FP code. The best way to learn a language (spoken language) is to immerse yourself in it and think of it. The same goes for programming languages.
Three years ago I started learning Clojure. At that time, I don't even know what is Lisp and what are functional programming languages. I said: Huh? really what is that? Can I do something useful with Lisp? I read a lot, studied a lot and even better, I got a job in Clojure!
Now programming in functional languages feels natural to me, it makes sense. Programming in data structures and functions are all of what I need. Simplicity!
One thing to keep in mind that functional programming languages aren't difficult by default and OOP languages aren't easy by default.
I've not read this book, but it sounds like quite a good fit for what you're looking for (and I'm very happy with the other Pragmatic Bookshelf books I've read)
Functional Programming Patterns In Scala And Clojure
From the blurb:
By using both the statically typed, type-inferred Scala and the dynamically typed, modern Lisp Clojure, you’ll gain a broad understanding of functional programming.
For each pattern, you’ll first see the traditional object-oriented solution, and then dig into the functional replacements in both Scala and Clojure.
Re: your piano question, you might find core.async and David Nolen's blog posts on UI design with core.async (specifically http://swannodette.github.io/2013/07/31/extracting-processes/) interesting.
In the blog post, he proposes that a user interface (and by extension, a piano), consists of 3 elements - event stream processing, event stream co-ordination and interface representation. And he shows that these are a much more powerful abstraction than the typical OOP Model View Controller. All pretty new though (I don't think core.async is even officially released yet). But if you're looking for the idiomatic Clojure way to model a piano, I think that it may well be along those lines...

Coming from C to C++ [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
HI all.
I have started a new job recently where I am supposed to work with C++/ I have been doing programming in C language for past 5 years. I am looking for ways to get me up to an acceptable level in OOP. I have all the basic concepts of C++ and OOP but don't have much experience of actual class designing.
What I really am looking for is ways to learn class library designing as I will be working in a team who is writing C++ libraries for other programmers to use. Please suggest principles like "responsibility assignment" which can help me design classes in general.
Give a loook to Bob Martin SOLID principles:
SRP The Single Responsibility Principle: A class should have one,
and only one, reason to change.
OCP The Open Closed Principle: You should be able to extend a classes
behavior, without modifying it.
LSP The Liskov Substitution Principle: Derived classes must be
substitutable for their base classes.
ISP The Interface Segregation Principle: Make fine grained
interfaces that are client specific.
DIP The Dependency Inversion Principle: Depend on abstractions, not
on concretions.
I know this isn't the type of answer you've been looking for; it's more like a extension of the other answers (already done and yet to come). I thought I'd add some general stuff...
Write one class declaration per .hpp file, one class definition per .cpp file. Name files like the class they contain. (It's surprising and frustrating to find how much code doesn't get this basic rule right.)
Be aware that C++ is a multi-paradigm language. Some things are better solved without a class hierachy. (Some things call for templates, some things are best done in good old procedural style.)
Learn about the Boost libraries, and how they do things. They're a good showcase of well-done C++, especially on the user interface side. And they are useful in your everyday work, too.
Read "Effective C++", "More Effective C++" and "Effective STL" by Scott Meyers. If in doubt, just get the first, and you'll find out why you should read the other two yourself.
Couldn't resist giving these basics, seeing a newcomer to the language that actually asks for advice before getting into lots of bad habits. ;-)
There are a number of posts here on SO dealing with this, for instance:
What is the best source to learn C++?
A good C++ book
In general, Scott Meyers books are a good place to start.
Books by Andrei Alexandrescu are also very good.
I still like Bjarne Stroustrup's book. It has several chapters devoted to design and it's also a great language reference. It can be pretty dense reading at times, but it's worth the effort.
I found C++ to be a great tool, but only after I really learned how to use it. Read all the references suggested here by others, and there's no substitute for practice!
The SOLID principles are good guides, but don't forget that you have to have concrete use cases if you are going to be able to do good OOD. If you are designing a class (for other programmers) to inherit from, you need at least three concrete (and as different/realistic as possible) cases where you actually inherit from the class, or you will not be able to see how the classes should work.
Try designing everything in UML before you code using proper sequence of diagrams down to class and sequence. Despite all (rightly) criticisms of UML, it will force you to treat program as a system of interacting objects and not sequence of code.
Most of "principles of OOP" are easily reduced to absurdity if you try to design program following them exactly. Refactoring is another story.
Otherwise, make sure you really know C++ and STL. Good or bad, STL is what is expected in C++ code.
Designing C++ class hierarchies for others to use is a minefield. I would highly recommend reading up on some of the common pitfalls in class design. Two books I suggest:
C++ Coding Standards (Herb Sutter & Andrei Alexandrescu). Packed full of concrete examples of how to create proper classes in an easy to understand way.
Effective C++ (Scott Mayers). How to write correct C++, starting from the transition from C to C++. A classic.
Refer this link. This pdf consists of "Design Principles and
Design Patterns"
http://www.objectmentor.com/resources/articles/Principles_and_Patterns.pdf
The above link will help u a lot.
Depending on how STL oriented your new job is, you'll either get praised, or shot, for reading: Modern C++ Design by Alexandrescu.
Even if you don't use any of the patterns in it, it will open a new world of C++ to you.
I'd put that book second on your reading list, after some Meyers books. Alexandrescu is pretty... intense.
It takes a few years to become proficient in C++. The books that have been suggested will help. I also suggest that you read Herb Sutter's Exceptional C++ series.
For the short term, you should find a C++ mentor to help you get up to speed in the new company. Each company has its own "culture" around C++. Dos and don'ts. This may be more relevant to your job than what you read. For example, your company may not use STL, so learning it may turn out be just an academic exercise. Many companies practice "Cargo Cult" programming - in this case, avoiding powerful but scary features of the language - so you may find you're frustrated that you can't use what you learn from the books.
It's hard for me to imagine trying to learn a language as complex as C++ just for the job. Reading all those books and practicing takes time. You can learn what you need for the job, and make a useful contribution. I think you have to love it to become proficient.
You should read Tony Albrecht's Pitfalls of Object Oriented Programming.
I recently started working with C++ too, and this is what I did:
First, I got the book C++ In Action from a coworker, and went through its 'Language' part, doing all the exercises. The 'Techniques' chapter is also an important one.
Then, the thing that helped me the most, I think, is reading a lot of my team's already written code and trying to understand the reason for everything in it. If your team members know how to code well, this is quite educating. And anyway, it definitely helps you understand the purpose and methods of your project, and what's expected of you.
Reading part the project's code might be something you'd have to do anyway, I believe (in order to use library functions, implement similar functions, or add to existing code), but sometimes people skip that part or do it very superficially.

Resources to learn C++ itself, not the basics of programming? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm something of a new, reluctant convert to C++ from a Pascal, Ruby, and PHP background. I haven't worked with Pascal since a few months of torture with "Delphi Turbo;" since then I've practically been eating and sleeping Ruby and PHP. I'm already well acquainted with object oriented programming and many various subjects.
My main trouble is that I already know the rudiments of C/C++ programming, less the actual experience of working with C++. I worked with C for long enough to realize that even without macros, etc, I didn't want to work with it. (Some of the disgust was from maintaining a CGI application in C, when accustomed to Pascal's automatic string management.) I know just enough C++ to be dangerous to myself and anyone else unwitting enough to use my "code."
I'd really like to work up to a good enough understanding of C++ to use libraries like Crypto++ and Boost without major problems or in-depth knowledge of the language's intricacies. I just need to figure out how to work with C++ without killing myself (either with C++, or with the long-standing dislike that I'm already battling).
What are effective resources that will teach me C++ without assuming that I must be retaught all basic programming? I'd rather not relearn concepts that I already know, unless the paradigm in C++ is significantly different. I'm also learning on my own time, so don't recommend me a book complex enough to need a guru to explain to me, please! And I have an effective budget of $0 for learning C++, so please keep suggestions to quality online resources or books common enough that I could likely find them at the library.
Read Effective C++ by Scott Meyers - it's a good guide for getting past the basics of C++ and showing how to write and use "correct" C++ code
The C++ FAQ Lite is a great resource.
I highly recommend Stroustrup: The C++ Programming Language (Third Edition). As the author of C++ he is the authority on the language, and the book is useful as a reference as much as it is for learning the language. It's common enough that most good general purpose libraries will have a copy. He goes into quite some depth on all the features of C++, including explanations of why certain design decisions were made in the language. Personally, I think this is the best book around for programmers to learn C++.
Once you have a good grip on core C++, David Abrahams and Aleksey Gurtovoy's book, C++ Template Metaprogramming, goes into further depth and provides many examples of how C++'s template system allows you to perform complex compile-time programming, a highly valuable skill these days. This one is a little less common but you can probably find it at a university library.
I can give you a couple of keywords you might want to research in more detail:
RAII (Is pretty much the technique that ensures you don't have to worry about memory leaks. Very convenient)
Generic Programming (The STL in particular. Experiment with iterators and the standard library algorithms, and see just how powerful these abstractions are. They're a key part of what I like about C++)
Functors (Perhaps too simple on their own, but the way they can be used instead of function pointers with the algorithms mentioned above is interesting)
And just get familiar with templates, and "mild" forms of template metaprogramming. (Traits classes, for example, and (partial) specializations.
And just keep an eye on the C++ questions here on SO. A lot of interesting topics are regularly brought up.
But the best advice is probably to keep it completely separate from C. Forget everything you learned about how to use C. It either doesn't apply in C++, or leads to inferior code that is harder to read and maintain.
It's an interesting language in its own right, and has a number of unique features. Leverage those, and it can actually be fun to work with C++. Treat it as an overengineered Java, PHP or C, and it'll just make you want to throw up.
You need to write code. A lot of code in C++. There is no substitute. You also need to read good code.
I agree with the suggestion for Scott Meyers' books though. Those are pretty good.
Part of your learning will be the leap from procedural programming to OO.
I would highly recommend the book "C++ Common Knowledge" by Stephen C. Dewhurst. Don't know if it's common enough to be found at the library (it's not at mine, but my library sucks for computer books that aren't 5-10 years out of date), but it does an excellent job of taking the complex aspects of C++ and making them easy to understand, without dumbing anything down for beginners. Definitely worth the investment.
To quote from the back of the book:
This book is for you if
You're no "dummy," and you need to get quickly up to speed in intermediate to advanced C++
You've had some experience in C++ programming, but reading intermediate and advanced C++ books is slow-going
You've had an introductory C++ course, but you've found that you still can't follow your colleagues when they're describing their C++ designs and code
You're an experienced C or Java programmer, but you don't yet have the experience to develop nuanced C++ code and designs
You're a C++ expert, and you're looking for an alternative to answering the same questions from your less-experienced colleagues over and over again
C++ Common Knowledge covers essential
but commonly misunderstood topics in
C++ programming and design while
filtering out needless complexity in
the discussion of each topic. What
remains is a clear distillation of the
essentials required for production C++
programming, presented in the author's
trademark incisive, engaging style.
Here is a link to a question with answers that should help you.
https://stackoverflow.com/questions/1227764/i-need-to-improve-my-c-skills-fast-is-this-realistically-possible/1227805#1227805
For effective stuff you can find online Cplusplus.com has a pretty good reference and information.
If you can find the book "C++ Common Knowledge" (Stephen Dewhurst) at the library or cheaply online, I would add that to the list posted on the StackOverflow link above as well as "The C++ Programming Language" (Stroustrup). Going through the questions under the C++ tag right here on SO should give you some good pointers and code examples to get you on your way.
Here's a list of good C++ books which teach you C++ rather than basics of programming.
Sit down and write some C++ code.