How to avoid dynamic cast in C++?

This post is just to know is there any alternate way from using dynamic_cast.
Is it supported in C++?
I tried with little program but it failed, can anyone direct me what could be
the problem in below code?

class Base
{
public:
virtual Base* getPointer();

};

Base* Base::getPointer()
{
cout<<"In Base Class" << endl;
return this;
}

class Derived : public Base
{
public:
Derived* getPointer();

};


Derived* Derived::getPointer()
{
cout<<"In Derived Class" << endl;
return new Derived;
}

int main()
{
Derived d;
Base* bPtr = &d;
Derived* ptr = bPtr->getPointer();
return 0;
}

Note: 1. This code is not getting compiled.
2. Gcc compiler is used for the compilation.
3. This code doesn't give any meaningfull implementation, it was
just written, to find alternate way of doing dynamic_cast.

Why is this compilation failure?

Waiting for the reply..

Cheers
Satish

Last edited on
This is perhaps a bad example.

When the compiler attempts to compile

bPtr->getPointer();

it knows to look at Base's declaration of getPointer() since bPtr is a pointer to a Base. It does not know
that bPtr is actually a pointer to a Derived, and therefore it does not look at Derived's declaration of
getPointer(). According to inheritance rules, Derived is-a Base, but the converse is not necessarily true;
hence the need for dynamic_cast.

Avoiding dynamic_cast's in C++ requires modification of design; there is no syntactic way to accomplish
it. If there is a specific case of dynamic_cast you are trying to avoid, you'll need to post the actual case/code.
Shouldn't Derived::getPointer() return a Base *?
helios, its not necessary. Overriding is valid as long as the signature and function name are same, C++ allows different return types there.
Last edited on
jsmith, getPointer() is virtual here and bptr points to derived object. So when compiler sees

bPtr->getPointer();

shouldn't "Derived::getPointer()" get called?
jsmith, I realized what you said. Compiler sees the static type of bptr during compilation, which is Base* and bptr points to Derived object during run-time.
n4nature said
helios, its not necessary. Overriding is valid as long as the signature and function name are same, C++ allows different return types there.


Are you confusing overloading and overriding?
Thanks Smith...
You have a valid explaination for my question...

Thanks to all for the answers.

With Thanks
Satish
Topic archived. No new replies allowed.