Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 605
Bruce Avatar asked Nov 26 '10 14:11

Bruce


2 Answers

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 ...
};
like image 186
Steve Jessop Avatar answered Sep 24 '22 19:09

Steve Jessop


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.

like image 41
David Rodríguez - dribeas Avatar answered Sep 22 '22 19:09

David Rodríguez - dribeas