Object slicing revisited | SoloLearn: Learn to code for FREE!

+1

Object slicing revisited

Hi, I still don't get how to avoid object slicing... std::vector<Base*> vec = { new Derived(), new Derived() }; Using smart pointers will cause the objects to get created and destroyed on the same line. I still want to use the vector's contents afterwards... But if I do the memory management manually like above, the base class' constructor keeps getting called, which leads me to not being able to call functions declared in the derived class :( Any help would be appreciated EDIT: The code above is just for illustration

5/24/2020 7:46:32 PM

Orville Vroemen

6 Answers

New Answer

+1

Thanks Dennis, here is basically what I'm trying to do(DON'T MIND THE MEMORY LEAK, I'll fix that later :P). https://code.sololearn.com/cFGYCk8uknJ6/?ref=app

+1

It's because operator<< is not a virtual function so the function does not appear in the class' virtual table and therefore it does not get called through polymorphism. Sadly, a friend function or operator can't be virtual so you have to do a little workaround. In both classes define this function: virtual void print() const { std::cout << *this; } The inheriting classes should also mark it as override for good practice. virtual void print() const override { std::cout << *this; } ( virtual is optional in the inheriting classes, but I like to type it anyway unless the class itself is marked as final, it will still be virtual even without the keyword ) Then, back at main call it like v.at(0)->print(); You could also move the entire definition of the friend operator to the print function, that's up to you.

+1

Right, thanks for the insight Dennis. The code now works as it should, although I did the virtual friend simulation with inline functions. https://code.sololearn.com/cFGYCk8uknJ6/#cpp

+1

Thanks anyways it really helped!

0

Can I see the rest of the code? There is nothing wrong with your vector. Here is an example using unique_ptr though: https://code.sololearn.com/cSL6v9kiKmng

0

That's a good solution too, I just went for the shorter answer because I was using my phone. :)