Static Casting is not working.What can be bug in it?

May 14, 2009 at 12:32pm
hi everybody .
I am trying to use static casting to downcast it .but its not working.Plz help me to find the bug in it .

#include<iostream>
#include<typeinfo>
using namespace std;

class Shape{
public:
virtual ~Shape()
{
}
};
class Circle:public Shape{
};
class Square :public Shape{
};

int main()
{
Circle c;
Shape* s=&c;
s=static_cast<Shape*>(&c);
Circle *cp=0;
Square *sp=0;
if(typeid(s)==typeid(cp))
cp=static_cast<Circle*>(s);
if(typeid(s)==typeid(sp))
sp=static_cast<Square*>(s);
if(cp!=0)
cout<<"It's a circle"<<endl;
if(sp!=0)
cout<<"Its a sqaure"<<endl;
}
Last edited on May 14, 2009 at 12:34pm
May 14, 2009 at 12:38pm
static_cast is not what you want. You want dynamic_cast.

May 16, 2009 at 2:18pm
but with dynamic cast its not working?
[:(]
May 16, 2009 at 4:20pm
Define "not working".
May 16, 2009 at 5:58pm
I think ajay16oct is a bit confused.
May 17, 2009 at 8:04am
"Not Working " is that even with dynamic_cast or with static_cast its not printing "It's a circle " and "Its a square".
since static_cast and dynamic_cast downcasting to the appropriate type..but nothing is working here..
I want to know from you guys why its not working
May 17, 2009 at 2:59pm
I don't often use typeid() (by "often" I mean "ever"), so I had to look this up. Here's a referral page:

http://cplusplus.com/reference/std/typeinfo/type_info/

Here's where your problem lies:

1
2
Circle *cp=0;
if(typeid(s)==typeid(cp))


There are two problems with this.

1) s is of type 'Shape*' and cp is of type 'Circle*', so this will always return false because the types are not the same. Therefore your casts are never happening.

2) 'cp' is a null pointer (doesn't point to anything) so you can't dereference it (if you try your program will crash).


What you're trying to do here is simple. In English, your desired if statement looks something like "If 's' points to a Circle". To translate that into more C++ friendly English, you could rephrase that as "If whatever 's' points to is the same type as a Circle". Which, in C++, looks like the following:

if(typeid(*s) == typeid(Circle))

Of course if you're using dynamic_cast you don't need typeid at all.

edit: to put that another way. What you're doing in your original post with typeid checks and static_cast is pretty much exactly what dynamic_cast does internally (automatically checks the types and only performs the cast if the type is correct).
Last edited on May 17, 2009 at 3:06pm
Topic archived. No new replies allowed.