Question

Let's say we have two classes:

class A:
{
   A(int a); // c'tor
   virtual ~A(); // d'tor
   FirstMethod(...);
   SecondMethod(...); 
}

class B:public A
{
   B(int a); // c'tor
   ~B(); // d'tor
   FirstMethod(...); 
   SecondMethod(...);
}

The two classes A and B have the exact same methods(same name and parameters but not necessarily the same functionality) and members, except for the destructor's name and the constructor's name, which are different. Now, let's say we have an object:

 A* aObject = new A();

and we do:

B* bObject= dynamic_cast<B*>(aObject);

Would the last casting succeed or that bObject will be NULL? or in other words, can the program distinguish between objects that are A* type and objects that are B* type?

Was it helpful?

Solution

Would the last casting succeed or that bObject will be NULL?

It would be NULL. Dynamic casting does not magically create a B. It only gives you a B* if you have an actual B to point to. Here, you only have a A.

OTHER TIPS

The dynamic cast will fail, but the compile will fail first. I know your intent, but I think you're trying to write dynamic_cast(aObject) instead of trying to cast the type. This is the compile failure. But after getting that corrected, the dynamic cast will still fail because aObject is not of type B* (it fails the is-a test). For it to work, B would have to be derived from A.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top