4

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

Community
  • 1
  • 1
user1198065
  • 210
  • 3
  • 10
  • 6
    You answered your own question. Here's a [good question](http://stackoverflow.com/questions/11792207/why-does-the-default-parameterless-constructor-go-away-when-you-create-one-with) on why. – chris Sep 04 '12 at 21:42

4 Answers4

7

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.

eq-
  • 9,986
  • 36
  • 38
5

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);
};
Alex1985
  • 658
  • 3
  • 7
0
  • You can either write a default constructor as suggested above, and write in your maing function:

    A* obj = new A();

  • You can write in your main function for example

    A* obj = new A(5);

  • You can set in your constructor

    public:
    A(int i=0) 
    { 
        cout << "My own  constructor!"; 
    }; 
    

    with which when you are creating an object of that class you can either write

    `A* obj = new A(5);`
    

    which will change the variable i to have a value 5
    OR you can just initialise your object like

    `A* obj = new A();` 
    

    which will leave the variable i with the default value 0.

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
DKralev
  • 1
  • 1
  • Wouldn't `A obj = new A(5);` require either a copy constructor or assignment operator unless declared `A* obj`? I'd go with `A obj(5);` if you want it on the stack and not heap. – Ghost2 Sep 05 '12 at 01:54
  • Oh My bad. I've been writing on c# lately and got mix up a little :) – DKralev Sep 05 '12 at 07:53
0

It is C++ convention. When you have written any user-defined constructors, it assumes that you will not need an implicit non-parameter constructor. It is understandable so just remember it.

Niklas Hansson
  • 503
  • 2
  • 16