Bruce
Bruce

Reputation: 35213

Why does copy constructor hide the default constructor in C++?

#include <iostream>
#include <conio.h>

using namespace std;

class Base
{
      int a;
public:
      Base(const Base & b)
      {
                 cout<<"inside constructor"<<endl;
      }   

};

int main()
{
   Base b1;
   getch();
   return 0;
}

This gives an error. no matching function for call to `Base::Base()' Why?

Upvotes: 5

Views: 1045

Answers (2)

Steve Jessop
Steve Jessop

Reputation: 279225

The default constructor is only generated if you don't declare any constructors. It's assumed that if you're defining a constructor of your own, then you can also decide whether you want a no-args constructor, and if so define that too.

In C++0x, there will be an explicit syntax for saying you want the default constructor:

struct Foo {
    Foo() = default;
    ... other constructors ...
};

Upvotes: 9

It does not hide the default constructor, but declaring any constructor in your class inhibits the compiler from generating a default constructor, where any includes the copy constructor.

The rationale for inhibiting the generation of the default constructor if any other constructor is present is based on the assumption that if you need special initialization in one case, the implicitly generated default constructor is most probably inappropriate.

Upvotes: 7

Related Questions