Constructor error parameterized c++

Asked

Viewed 200 times

1

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

1 answer

0


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

Of 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 take 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 as follows:

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

private:
   int valor;

};
  • Thank you! That’s what I was wondering, what kind of mistake was going on.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.