C ++ virtual inheritance and modeling / copying constructor confusion

I have the code below:

class A
{
};

class B: public virtual A
{
public:
    B()
    {
        cerr << "B()";
    }
    B(const A& a)
    {
        cerr << "B(const A&)";
    }
};

class C: public B
{

};

int main(int argc, char **argv)
{
    B *b = new B(C());
}

To my surprise, B (const A & a) is not called. Why is this?

+3
source share
2 answers

B also has an implicitly declared copy constructor declared as

B(const B&);

This implicitly declared member function is called, because it better matches the argument types Cthan your ads to users constructor B(const A&).

+8
source

This is what I got when I tried clang++ -cc1 -ast-dumpin your code

class B : virtual public A {
    class B;
public:
    B() : A() (CompoundStmt 0xb85950 <a.cpp:9:5, line:11:5>)


    B(A const &a) : A() (CompoundStmt 0xb859c0 <a.cpp:13:5, line:15:5>)


    inline B &operator=(B const &) throw();
    inline void ~B() throw();
    inline B(B const &) throw() : A((ImplicitCastExpr 0xb86a10 <a.cpp:5:7> 'clas
s A const' <UncheckedDerivedToBase (virtual A)> lvalue
  (DeclRefExpr 0xb869ec <col:7> 'class B const' ParmVar='' 0xb86170))
) (CompoundStmt 0xb86ab0 <a.cpp:5:7>)

, B () ctor.

inline B(B const &) throw():, C . B(const A& a), .

+1

Source: https://habr.com/ru/post/1765831/


All Articles