Reputation: 5649
This code returns me an error whenever I try to run this code. Can some one please help me.
struct m
{
virtual int s( )
{
return 1;
}
};
struct n : public m
{
int s( )
{
return 2;
}
};
int o( )
{
n* p=new m;
m* q=dynamic_cast<p>;
return q->s( );
}
Upvotes: 3
Views: 181
Reputation: 632
Two problems, first you can't allocate an m and call it n in the first line of main. You have a syntatic error in the dynamic_cast. It is dynamic_cast<new type>(some var)
.
Upvotes: 0
Reputation: 77722
Next time, please tell us what the error is!
I suppose you're saying that there is a compile error because you're not using dynamic_cast right? You probably meant to say
m* q=dynamic_cast<m *>(p);
In general, dynamic_cast is the devil. Most implementations are insanely slow and might go as far as going string-based class name checks. Unless you really, absolutely need to use dynamic_cast, please use any other method available (such as static_cast).
Upvotes: 2
Reputation: 523214
These C++ cast operators should be used as
dynamic_cast<newType>(variable)
In your case,
m* q = dynamic_cast<m*>(p);
BTW, are you confusing the role of m
and n
? n* p = new m
is a syntax error because a base class instance cannot be implicitly converted to a derived class instance. In fact, base → derived is the situation where you actually need dynamic_cast
, not the other way around (no casting is needed).
Also, consider giving meaningful names to objects.
Upvotes: 7