Why are constructors called if they are not inherited?

code prints all constructors. I read that constructors are not inherited when we derive a class from another class. then why creation ccalls constructors from banda

class A
{
public:
  A()  { cout << "A constructor called" << endl; }
};

class B
{
public:
  B()  { cout << "B constructor called" << endl; }
};

class C: public B, public A  // Note the order
{
public:
  C()  { cout << "C constructor called" << endl; }
};

int main()
{
    C c;
    return 0;
}
+4
source share
7 answers

When the document you are reading is not inherited, the constructors mean that if the class Adefines a constructor A::A(int x), then the child class Bwill not automatically have a constructor that accepts int.

; . , , . , . , . , , :

class A
{
public:
  A(int x)  { cout << "A constructor called" << endl; }
};

class C: public A
{
public:
  C()  
  : A(7)  /* compilation will fail without this line */
  { cout << "C constructor called" << endl; }
};
+5

, ,

. , , .

, :

struct A
{
   A(int) {}
};

struct B : A
{
   B() : A(0) {}
};

, :

B b(10);

A(int) B.

.

c b a

, B, B. A , - B, A, .

A -part B.

  • A :

    B() : A(0) {}
    
  • , A.

    B() {}
    

    :

    B() : A() {}
    

    , A , , .

C, :

C()  { cout << "C constructor called" << endl; }

C() : B(), A() { cout << "C constructor called" << endl; }

B::B() A::A() C.

+2

.

.

, , . . , .

, . . , . "".

, . , , ( , ).

.

0

, . , , . , .

0

" " , C , , B, B C. , : .

, , .

, , .

: - .

0

, ++ 11 ,

class A
{
    public: 
        A(int x) {}
};

class B: public A
{
};

int main(void)
{
    B b(5);
    return 0;
}

, A(int) . B, A(int)

class B: public A
{
     using A::A;
};

ctors , - C c.

0

++ , . :

class A {
    public:
        A() {
            std::cout << "Constructor A" << '\n';
        }
};

class B : public A {
    public:
        B() {
            std::cout << "Constructor B" << '\n';
        }
};

class C : public B {
    public:
        C() {
            std::cout << "Constructor C" << '\n';
        }
};

C C, B A. , C, , . ( A C). - , - .

. , ( C A).

0

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


All Articles