Up Casting Using References Instead Of Pointers

76 Views Asked by At

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?

1

There are 1 best solutions below

9
user17732522 On

A& a = *b; behaves exactly in the same way that A* a = b; would, i.e. a will be a reference bound to the A base class subobject of the B object 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:

B* b2 = static_cast<B*>(a);

if a is a A* or

B& b = static_cast<B&>(a);

if a is a A&. (Of course both have undefined behavior if the A object referred to by the right-hand side isn't actually a base class subobject of an B object.)