Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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&)

like image 479
user1198065 Avatar asked Dec 15 '22 19:12

user1198065


2 Answers

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.

like image 135
eq- Avatar answered May 10 '23 18:05

eq-


No, according to standard default constructor is not generated in such case. However, in C++11 you can declare that you want default constructor to be generated by using:

class A {
public:
  A() = default;
  A(int);
};
like image 31
Alex1985 Avatar answered May 10 '23 19:05

Alex1985