Heredar constructores


¿Por qué este código:

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

class B: public A
{
};

int main(void)
{
    B *b = new B(5);
    delete b;
}

Dan lugar a estos errores:

main.cpp: In function ‘int main()’:
main.cpp:13: error: no matching function for call to ‘B::B(int)’
main.cpp:8: note: candidates are: B::B()
main.cpp:8: note:                 B::B(const B&)

¿No debería B heredar el constructor de A?

(esto está usando gcc)

Author: Rohit Vipin Mathews, 2008-12-07

6 answers

En C++03 los constructores estándar no se pueden heredar y necesita heredarlos manualmente uno por uno llamando a la implementación base por su cuenta. Si su compilador soporta el estándar C++11, hay una herencia de constructor. Para más información ver Artículo de Wikipedia C++11. Con el nuevo estándar escribes:

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

class B: public A
{
     using A::A;
};
 282
Author: Suma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-23 00:13:12

Los constructores no se heredan. Son llamados implícita o explícitamente por el constructor hijo.

El compilador crea un constructor predeterminado (uno sin argumentos) y un constructor de copia predeterminado (uno con un argumento que es una referencia al mismo tipo). Pero si quieres un constructor que acepte un int, tienes que definirlo explícitamente.

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

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

UPDATE : En C++11, los constructores pueden ser heredados. Vea la respuesta de Suma para más detalles.

 82
Author: Avi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-15 21:31:42

Debe definir explícitamente el constructor en B y llamar explícitamente al constructor para el padre.

B(int x) : A(x) { }

O

B() : A(5) { }
 6
Author: grepsedawk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-07 06:33:29

Esto es directamente de La página de Bjarne Stroustrup :

Si así lo desea, todavía puede dispararse en el pie heredando constructores en una clase derivada en la que define nuevas variables de miembro que necesitan inicialización:

struct B1 {
    B1(int) { }
};

struct D1 : B1 {
    using B1::B1; // implicitly declares D1(int)
    int x;
};

void test()
{
    D1 d(6);    // Oops: d.x is not initialized
    D1 e;       // error: D1 has no default constructor
}
 3
Author: nenchev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-11 12:58:36

El código correcto es

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

class B: public A
{
      public:

     B(int a):A(a){
          }
};

main()
{
    B *b = new B(5);
     delete b;
}

El error es b / c La clase B no tiene constructor de parámetro y en segundo lugar debe tener inicializador de clase base para llamar al constructor de parámetro de clase Base constructor

 1
Author: Iqbal Haider,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-20 07:48:08

¿Qué tal usar una función de plantilla para enlazar a todos los constructores?

template <class... T> Derived(T... t) : Base(t...) {}
 1
Author: Pradu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-07 18:40:47