Derived classes in C++
Hi, just looking at derived classes, the following example doesn't give me the expected results, i.e. using the derived classes functions.
Code:
#include <iostream> Code:
test Code:
test |
|
merci
|
You cannot put a derived class object into a container of base class objects.
Trying to do so will make a base class object by copying the base class portion of the derived class object you tried to insert. Virtual functions would be the answer if you were trying to use a base class reference or pointer that points to a derived class object and you wanted the derived class version of the function. But containers of polymorphic objects represent a much harder problem in C++. You can have a container of base class pointer, pointing to polymorphic objects (then you would still need to make the functions virtual to achieve what you want). But a container of pointers introduces a bunch of extra issues involving object ownership (decision of when to delete) as well as the syntactic overhead of the extra level of indirection. |
Simpler example simplifies debugging
brazilnut, I usually start with simpler examples to simplify debugging. After the smaller pieces work, putting them into bigger pieces either will work, or the problem is in the bigger pieces. I inserted the following lines before the pushback calls:
Code:
n.print(); Quote:
|
ArthurSittler -
No, the main problem was that the OP wasn't considering the importance of virtual functions. posixculprit told him, and brazilnut totally got the message. And Johnsfine's note about "object pointers" vs. "stack objects", and the whole issue of "copy semantics", was absolutely correct. Another (of the many reasons!) I believe C++ sucks ... at least as a beginners language. Brazilnut - as a courtesy, you might want to "thank" posixculprit (the blue "thumbs up" icon) and/or mark his thread as "useful" (I did the same). You might also want to mark the thread as "solved" (assuming the problem is indeed resolved). |
thanks
Thank you, brazilnut, paulsm4, and posixculprit.
The compiler never complained about any type conflict when it was asked to use the derived types. It simply used the objects' base classes. That is the type declared for the container. Not as I expected, either. |
paulsm4
I do use the thanks link, but it doesn't seem to work half the time, it's actually registered the thanks from last night now, so? Also I don't see a solved link and can't change the title from edit... so there's a thanks up for grabs for the first to shed some light... Cheers! |
Quote:
Quote:
|
All times are GMT -5. The time now is 10:37 AM. |