-1

given the next code:

class A {
      // ...
};

class B : public A {
      // ...
};

And:

A a;   
B b;    
A& ab = b;   
ab = a; 

Will be a slicing in the last line of this code? Why?

StackUser
  • 309
  • 2
  • 10

1 Answers1

1

There will not be slicing. But there will be called the copy assignment operator for the class A due to the static type of the reference ab.

Consider the following program

#include <iostream>

struct A 
{
    A & operator =( const A & )
    {
        std::cout << "A::operator = is called" << std::endl;
        return *this;    
    }
};

struct B : A 
{
    B & operator =( const B & )
    {
        std::cout << "B::operator = is called" << std::endl;
        return *this;
    }
};

int main() 
{
    A a;   
    B b;    
    A &ab = b;   
    ab = a; 

    return 0;
}

Its output is

A::operator = is called

You may not reassign a reference such a way that it would refer another object.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335