PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 10, 2022

[FIXED] When does reference casting slice objects?

 July 10, 2022     c++, casting, object, reference     No comments   

Issue

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?


Solution

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 assign a B object to an A object, like A a = b;, which will only copy the inherited A portion of b.



Answered By - BoP
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing