简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM