Search code examples
c++constructordefault-constructor

If we overload a constructor in c++ does the default constructor still exist?


Possible Duplicate:
Why does the default parameterless constructor go away when you create one with parameters

I wrote the following program

#include <iostream>
class A {
public:
    A(int i) {std::cout<<"Overloaded constructor"<<std::endl;}
}

int main() {
A obj;
return 0;
}

when I compile the program I am getting the following error:

no matching function to call A::A() candidates are: A::A(int) A::A(const A&)


Solution

  • The existence of the default constructor in this case depends on whether you define it or not. It will no longer be implicitly defined if you define another constructor yourself. Luckily, it's easy enough to bring back:

    A() = default;
    

    Do note that the term "default constructor" refers to any constructor that may be called without any arguments (12.1p5); not only to constructors that are sometimes implicitly defined.