When does reference casting slice objects?

  c++, casting, object, reference

Take a look at this piece of code:

#include <iostream>


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

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



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?

Source: Windows Questions C++

LEAVE A COMMENT