Wednesday 7 March, 2007

Beauty of dynamic_cast in C++

Recently I came across this strange behavior of dynamic_cast in my R&D work..

What do you think this program will print out?

#include

class Base
{
public:
virtual ~Base() {}

void AddRef()
{
std::cout<< "Resolved dynamic cast\n";
}
};

class CompositeBase : public Base
{
public:
virtual ~CompositeBase() {}
};

class Dependent
{
public:
virtual ~Dependent() {}
};

class CompositeDependent : protected Dependent
{
public:
virtual ~CompositeDependent() {}
};

class RealObj : public CompositeBase, public CompositeDependent
{
public:
virtual ~RealObj() {}
};

int main (int argc, char * const argv[]) {

Dependent* pDep = (Dependent*)( new RealObj() );

Base* pBase = NULL;

try
{
pBase = dynamic_cast (pDep);
}
catch(...)
{
printf("Exception \n");
}

if(pBase)
pBase->AddRef();

delete pDep;

return 0;
}

2 comments:

Science Stuff said...

OH!!!! Fully technical....
Good blog daaa!!

Shrinidhi said...

Thanks a lot... I successfully wasted 5 minutes of my valuable time!!