tags:

views:

115

answers:

2

I just found my code like this does not compile right? Is there any compiler-provided constructor here?

class A
  {

   private:   
      A(const A& n);

  };


int main()
{
        A a;
}

The error is test.cpp:18: error: no matching function for call to ‘A::A()’ test.cpp:11: note: candidates are: A::A(const A&)

I am using g++ under Ubuntu 8.04

+7  A: 

The compiler will provide for you

  1. the default constructor A() if and only if there are no user-defined constructors, and
  2. the copy constructor A(A const &) unless you provide either of the four possible copy constructors A(A cv &), where cv is any combination of const and volatile.

In your case, you've declared your own copy constructor, which means that the compiler will provide neither of the above.

The line A a; needs an accessible default constructor to compile.

avakar
wow...I thought default constructor will be provided.....because I just provided the copy constructor. I don't know default constructor and copy constructor are related.
skydoor
To C++ both are forms of a constructor and a way to create objects for the corresponding type.
ardsrk
if I declare only an operator assignment, will the default constructor be declared implicitly?
skydoor
They are related in that the copy constructor is (a special kind of) a constructor and providing your own constructor (copy or not) will suppress the automatic generation of the default constructor.
avakar
skydoor, yes, declaring the assignment operator will have no impact on the automatic generation of the default constructor.
avakar
Assignment is unrelated to object construction. In assignment say `a=b` both objects a and b are already constructed and "a" must now get a copy of b depending on the semantics of your application. So, yes if you only declare an assignment operator C++ will still declare a default constructor for you implicitly.
ardsrk
+3  A: 

The constructor you declared private in class A is a copy constructor.

Whenever you provide a parameterised constructor for a class C++ won't provide a default constructor ( one taking no arguments ). You have to explicitly define the default class constructor for your class.

ardsrk