0

I have an issue with Dynamic cast with inheritance.

I have Shape which is a base class and Rectangle which is a deviated class.

In my Rectangle.h file, I have the following

class Rectangle: public Shape

In my main class, I create a vector of Shape class named record

std::vector<Shape> record;

In my Shape.h file, I have the virtual function computeArea().

virtual double computeArea();

My Rectangle.h file contains the function double computeArea()

I am trying to dynamic cast the Shape into Rectangle to compute the area

for(int i=0; i < record.size(); i++)
    {
        cout << record[i].getName() <<endl;
        if(record[i].getName() == "Rectangle")
        {
            Rectangle& rectest = dynamic_cast<Rectangle&>(record[i]);
            cout << rectest.computeArea() << endl;
        }
    }

However,I got this error "terminate called after throwing an instance of 'std::bad_cast' what(): std::bad_cast Aborted"

Any one know what could be the issue?

Thank you.

Lawrence Wong
  • 1,129
  • 4
  • 24
  • 40
  • 2
    You cannot store polymorphic objects in containers without making them pointers, regular or smart. There's lots of duplicates on this site explaining what's wrong (object slicing) and what needs to be done. [Here is an example](http://stackoverflow.com/a/37911600/335858) – Sergey Kalinichenko Oct 30 '16 at 11:33
  • Hi there. Sorry for asking a duplicate question. I am pretty new in c++. Will take a look at the object slicing link above. Thanks! – Lawrence Wong Oct 30 '16 at 11:36
  • to solve the problem of object slicing use pass by reference or by pointers not by value – Raindrop7 Oct 30 '16 at 12:51

0 Answers0