Home > Software engineering >  When does reference casting slice objects?
When does reference casting slice objects?

Time:12-07

Take a look at this piece of code:

#include <iostream>


class A{
public:
    int x;
    
    virtual void f(){std::cout << "A f\n";}
    
};

class B: public A
{
public:
    int y;
    
    void f() {std::cout << "B f\n";}
};



void fun( A & arg)
{
    std::cout << "fun A called" << std::endl;
    arg.f(); 
    // arg.y = 222; - this gives error, compiler's work?
    arg.x = 2223333;
}
void fun(B & arg){
    std::cout << "fun B called" << std::endl;
    arg.f();

}

int main()
{
    B b;
    b.y = 12;
    b.x = 32;

    fun(static_cast<A&>(b));
    
    std::cout << b.x << " " << b.y << std::endl;
    
    return 0;
}

What exactly happens when I reference cast b into A&? I'm guessing a reference to type A 'arg' is created in a funtion 'fun()' and now it's only compiler's work to differentiate types? Meaning no actual object was created and no slicing occurred and it's still the same object in memory, however compiler will treat it as type A? (meaning after function call I can safely use b as type B?)

I assumed that's true, because the vptr of the instance didn't change (arg of type A called B's virtual function override), but I'm not completely sure what's going on behind the scenes during reference casting.

Also, if I assign static_cast<A&>(b) to a new object of type A, I assume that's when the construction of a new object of type A and slicing occurres?

CodePudding user response:

Yes, you seem to have got this. :-)

A B is also an A (by inheritance), so it can bind to either A& or B&. Nothing else happens, it is just a reference to the existing object.

The slicing happens if you do A a = b;, which will only copy the first half of b.

  • Related