Printing from derived classes | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Printing from derived classes

class Shape{ private: char *name; }; class Circle:public Shape{ private: int radius; }; class Rectangle:public Shape{ private: int side1,side2; }; int main() { Shape **s; s=new Shape *[2]; s[0]=new Circle(2); s[1]=new Rectangle(2,3); cout<<*s[0]; cout<<*s[1]; } How to print information for the Circle and Rectangle objects? I tried with dynamic_cast in the Shape class but the program wont execute because the derived classes aren't declared yet, and i tried overloading the << operator in the derived classes but the program will only use the overloaded << operator from the Shape class. Any suggestions, please?

25th May 2021, 10:24 AM
Mihail
Mihail - avatar
4 Answers
+ 2
If I got the problem right, you could do something like this, i.e. shift the actual printing to a virtually overriden method that is then called from the overloaded insertion operator: https://code.sololearn.com/c5TIXWw2Gwk6/?ref=app
25th May 2021, 12:00 PM
Shadow
Shadow - avatar
+ 2
I'm confused by the Shape **s line, why use double pointer when you are making a list? Please save the full version of the code (with the << operator overload etc.) in SoloLearn, and share the link to the saved code instead, for a clearer view on the problem. https://www.sololearn.com/post/75089/?ref=app
25th May 2021, 11:29 AM
Ipang
+ 1
It's not a double pointer. It's a dynamic array of pointers.
25th May 2021, 11:40 AM
Mihail
Mihail - avatar
+ 1
Thanks, it worked. :)
25th May 2021, 4:29 PM
Mihail
Mihail - avatar