michalt38
michalt38

Reputation: 1203

Creating base class object with a derived class

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?

Upvotes: 1

Views: 54

Answers (1)

abhiarora
abhiarora

Reputation: 10460

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

Upvotes: 1

Related Questions