email naive email naive - 22 days ago 6
C++ Question

Two questions about casting objects in cpp

Question A

If I have two classes: "father", and "MyClassa" and I want to do this:

father* a;
MyClassa b;
a = &b;
((MyClassa *)a) - > b();


I can do the casting like in the sample above (
b()
is a function belonging to
MyClassa
class and not found in
father
class).

But when I do this:

father* a;
MyClassa b;
a = &b;
a = ((MyClassa *)a);
a->b();


It doesnt work for me and tells me that he
b()
function not exist in that class (like the casting didn't work).

What are the differences between these two code samples actually and what is causing this differences?

Question B

When I use 'dynamic_cast' to cast a father to be a child like this:

Father * fp= new Father;
Child * cp = dynamic_cast<Child *> fp;


It returns me a '0' value to the pointer.
But when I do the same with reference:

Father & fp= new Father;
Child & cp = dynamic_cast<Child &> fp;


It raises an error 'bad casting'.

Why is there a difference?

Answer

in this line

a = ((MyClassa *)a);

the term gets casted to MyClassa* but then back to father* (in the assignment) so you end up with a father*.

Regarding your second question: It's impossible to cast the reference from the father to the child, and also "wrong" in terms of polymorphism