I wonder if the following up-casting is valid? And if yes, is it possible to down-cast in the same way?
class A {
public:
A(){ cout << "A constructor\n";};
A(const A& a){ cout << "A copy constructor\n"; };
};
class B : public A {
public:
B(){ cout << "B constructor\n";};
B(const B& b){ cout << "B copy constructor\n"; };
};
int main(){
B* b = new B;
cout << "--------\n";
A& a = *b;
return 0;
}
I got no output from doing A& a = *b;, does this mean that doing this is equivalent to up-casting?
A& a = *b;behaves exactly in the same way thatA* a = b;would, i.e.awill be a reference bound to theAbase class subobject of theBobject or a pointer to the same subobject, respectively. It technically does however not involve any conversion (which is what you erroneously call a "cast"), instead it is just reference initialization.But neither of these initializations ever have any side effects, nor could they ever involve creation of a new object, a constructor call or any other function call.
Downcasts are possible in the exact same way as well and also have no side effects:
if
ais aA*orif
ais aA&. (Of course both have undefined behavior if theAobject referred to by the right-hand side isn't actually a base class subobject of anBobject.)