简体   繁体   中英

strange copy constructor behavior in inherit tree

i have three class types: Base->Center->Child, and i want to make it posible to construct child type from parent type, so i declared them like this:

class Base {
public:
    Base(void) {cout << "Base()" << endl;}
    virtual ~Base(void) {}
    Base(const Base &ref) {cout << "Base(const Base &)" << endl;}
};
class Center : public virtual Base {
public:
    Center(void) : Base() {cout << "Center()" << endl;}
    Center(const Base &ref) : Base(ref) {cout << "Center(const Base &)" << endl;}
};
class Child : public virtual Center {
public:
    Child(void) : Center() {cout << "Child()" << endl;}
    Child(const Base &ref) : Center(ref) {cout << "Child(const Base &)" << endl;}
};

it's OK to call it like this: (calling Center and Base's copy constructor)

Base base;
Center center(base);

.
however, these code act unexpectly:

Child child(base);

the output is:

Base()
Center(const Base &)
Child(const Base &)

why called Base(void) instead of Base(const Base &)?

SOLVED (many thanks to Dietmar Kühl and Adam Burry)
two method:

1. add Base(const Base &) to Child, which would looks like this:
   Child(const Base &ref) : Base(ref), Center(ref) {}
2. or, remove virtual inheritance, which would looks like this:
   class Center : public Base {...}
   class Child : public Center {...}

The argument to a virtual base class is provided by the most derived class, not by an intermediate class. If you want to pass the argument you received for Child to the Base , you need to implement your Child constructor like this:

Child::Child(Base const& other)
    : Base(other)
    , Center(other)
{
}

BTW, it is unusual to use (void) instead of () to indicate that the function doesn't take any arguments in C++: the void was at some point necessary in C to distinguish between a variable argument list function and a function taking no argument (I don't know if this is still the case in C11). In C++ an empty pair of parenthesis always indicated an empty argument list.

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