1

Hi, I am getting errors with RTTI. In this program I have an Abstract base class with virtual function area() and two derived classes.

I defined a polymorphic function and passed the derived object as argument to it which has reference to the base class as argument. I used typeid opeator to find RTTI and execute a function which is not defined in the Abstract base class. But I am getting the error as follows.

class poly
{
public:
virtual void area(void)=0;
};
class square : public poly
{
void area(void ) { cout<<" area : square " ;}
virtual void display(void) { cout<<" I am square ";}
};
class rect : public poly
{
void area(void) { cout<<" area : rectangle ";}
};
void print(poly &abc)
{
abc.area();
if(typeid(abc)==typeid(square))
abc.display();
}
int main()
{
square s;rect r;
print(s);
}

Eroor : class poly doesnot have disp function as member

could you please help in finding out the reason behind this error

Votes + Comments
code tags on first post award!
3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by __avd
0

Eroor : class poly doesnot have disp function as member

could you please help in finding out the reason behind this error

The compiler is right, "class poly" doesn't have a disp() function as a member. But the class 'square' does.

So change this line: void print(poly &abc) to this: void print(square &abc) and that should solve your problem.

Also don't forget to make the other memberfunction public: !

0

Use static_cast,

void print(poly &abc){
   abc.area();
   if(typeid(abc)==typeid(square))
      static_cast<square*>(&abc)->display();
}

PS: display() must have public access.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.