1

I have the following code:

class A {
public:
    A() { cout << "A()" << endl; }
    void f() { cout << "A" << endl; }
};

class B : public A {
public:
    B() { cout << "B()" << endl; }
    void f() { cout << "B" << endl; }
    void ff() { cout << "ff()" << endl; }
};

int main()
{
    A a = B();
    B b;
    a = b;
}

How calling A a = B(); will be different from A a = A();? Why is the conversion from derived class to base class possible?

michalt38
  • 1,193
  • 8
  • 17
  • `How calling A a = B(); will be different from A a = A();?` During the execution of this line, the `B` constructor will be executed, in addition to `A`. After this line is executed - the objects stored in `a` will be exactly the same due to [slicing](https://stackoverflow.com/questions/274626/what-is-object-slicing). – Algirdas Preidžius Apr 23 '20 at 10:57

1 Answers1

1

When you do A a = B();, copy constructor of class A should be invoked after default constructor of class B has been invoked (Note: Compiler may remove unnecessary copy using copy elison).

A(const A& other)
{

}

Since, object of class B can be passed to copy constructor of class A, it will be allowed but you may experience object-slicing.

If you are curious to know "how is it possible to pass a derived class object to a method accepting a reference to the base class", read the following:

  1. Is it possible to pass derived classes by reference to a function taking base class as a parameter
abhiarora
  • 9,743
  • 5
  • 32
  • 57