Question

I have written this code in MS Visual Studio Express 2012 to see the rtti behavior.
But it is not working as expected.
What is wrong in my code?

Shape.h

class Shape
{
public:
    Shape(){}
    virtual ~Shape(){}
    virtual double area() = 0;
};

class Square : public Shape
{
    int a;
public:
    ~Square(){}
    Square(int );
    virtual double area();
};

class Rectangle : public Shape
{
    int l;
    int b;
public:
    ~Rectangle(){}
    Rectangle(int,int);
    virtual double area();
};

class Circle : public Shape
{
    int r;
public:
    ~Circle(){}
    Circle(int);
    virtual double area();
};

ShapeMain.cpp

int main()
{
    Shape* c = new Circle(4);
    cout<< "Area of circle:" << c->area() << endl;
    cout << typeid(c).name();

    Shape* s = new Square(4);
    cout<< "Area of square:" << s->area() << endl;
    cout << typeid(s).name();

    Shape* r = new Rectangle(4,5);
    cout<< "Area of rectangle:" << r->area() << endl;
    cout << typeid(r).name();

}

Output

Area of circle:50.24
class Shape *           //Expected class Circle*
Area of square:16
class Shape *           //Expected class Square*
Area of rectangle:20
class Shape *           //Expected class Rectangle*   
Was it helpful?

Solution

typeid() only actually performs an RTTI lookup when passed an lvalue of a polymorphic type. Shape is a polymorphic type, but you aren't passing a Shape lvalue, you're passing a Shape*. So when you are passing c, s and r to typeid(), it reports the static type of those expressions, which is Shape*.

To get a run time lookup you can either dereference your pointer: std::cout << typeid(*r).name() << std::endl;

or you can keep references directly:

Circle circle{4};
Shape& c = circle;
cout << "Area of circle:" << c.area() << endl;
cout << typeid(c).name() << endl;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top