Why aren't C ++ constructors inherited?

Why does this code need a built-in pass-through constructor for Child? I would think that this will not happen, but the compiler (gcc and VS2010) complains when I delete it. Is there an elegant workaround? It is simply pointless to embed this pad in child classes.

class Parent
{
public:
  Parent(int i) { }
};

class Child : public Parent
{
public:
  Child(int i) : Parent(i) { }
};

int main()
{
  Child child(4);
  return 0;
}
+5
source share
7 answers

Because the following is absolutely true:

class Parent
{
public:
    Parent(int i) { }
};

class Child : public Parent
{
public:
    Child() : Parent(42) { }
};

How should the compiler guess if you want the derived child to have a redirected constructor? And in the case of multiple inheritance, the set of constructors from two types may not coincide; when transferring a constructor from base class A, which constructor should be called in base class B?

, , . , : , , , .

+12

, , , ( ).

Parent , , i.

Child , Parent, .


, ++ 0x. , ++ 0x.

+4

, ++ . , ?

class Parent1
{
public:
  Parent1(int i) { }
};

class Parent2
{
public:
  Parent2(int i) { }
};

class Child : public Parent1, public Parent2
{
};
+3

class Parent
{
public:
  Parent(int i) {this.i = i; }
  Parent() {this.i = 0;}
private:
  int i;
};

class Child : public Parent
{
public:
  Child(int i) : { }
};

int main()
{
  Child child(4);
  return 0;
}

, Parent. , Parent , long, , int? int long?

, - , , (no-arg all args having defaults). .

+1

?

++ 11 ( , ) :

class Parent
{
public:
  Parent(int i) { }
};

class Child : public Parent
{
public:
  using Parent::Parent; // inherits Parent(int)
};

int main()
{
  Child child(4);
  return 0;
}
+1

, ctr , .

( ), , , , i, .

0

, , , (, ). , -, , int, .

0

All Articles