Parameterized constructor error c ++

1

What happens when a class with parameterized constructor is created, without default constructor, and the object of this type is called without argument in constructor in c ++? Does compilation error occur? exception?

    
asked by anonymous 17.06.2015 / 14:38

1 answer

0

In C ++ when you declare a parameterized constructor, the compiler will not generate the default constructor (constructor without parameters).

From standard 12.1 / 5:

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a default constructor is implicitly declared.

You can do a little test:

class Teste {
public:
    Teste(int v) { valor = v; }   

private:
   int valor;

};

int main(int argc, char *argv[]) {

     Teste t;  //irá gerar erro de compilação  
     return 0;

}

To complete, you can tell the compiler to generate the default constructor regardless of any other constructor in the following way:

class Teste {
public:
    Teste() = default;
    Teste(int v) { valor = v; }   

private:
   int valor;

};
    
17.06.2015 / 14:50