3

Can someone tell me why would the compiler give an error for this.

class A
{
private:
 int data;
public:
 A();
 A(A& a) { this->data = a.data; }
};

void main()
{
 A a();
 A b(a);
}

The error I get is this.

error C2664: 'A::A(A &)' : cannot convert parameter 1 from 
 'A (__cdecl *)(void)' to 'A &'
MetallicPriest
  • 29,191
  • 52
  • 200
  • 356

3 Answers3

9
A a();

That is a forward declaration of a function which returns an A and takes no arguments. So, you're trying to pass a function pointer to your constructor, which of course doesn't work as no such constructor exists. If you want to use the default constructor use:

A a;

Of course, that constructor is not defined. You'll need to add a definition (you only wrote a declaration).

As an aside; main is defined to return an int, and you should take a const reference in your constructor.

A(const A &other) : data(other.data) {}
Ed S.
  • 122,712
  • 22
  • 185
  • 265
1

For a start it should be int main() and secondly the constructor `A() does not have a body

Also it should be A a; not A a();

EDIT

Better still A(A& a) { this->data = a.data; }should read A(const A& a) { this->data = a.data; }

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • Shouldn't the second line be A b(&a)? Just a guess, I'm totally new to C++. – Thomas Weller Jan 24 '14 at 19:00
  • @ThomasW.: No, that would produce a pointer. No special syntax is needed for passing a reference. – Ed S. Jan 24 '14 at 19:01
  • @ThomasW. Nope. `&a` returns a pointer, the type `A*` in fact. The type of `b` is `A`. You can't initialize a pointer with a non-pointer type. The types have to match. We do `A b(a)` because `b` will be initialized with a copy of `a`. – David G Jan 24 '14 at 19:02
  • Response to your edit: in addition to that, you should use the member initializer list `A(const A& a) : data(a.data) { }` – David G Jan 24 '14 at 19:19
-1

Try this:

class A
{
public:
  int data;
public:
  A(){this->data = 0;}
  A(A& a) { this->data = a.data; }
};

int main()
{
  A a;
  A b(a);
}

In Main, the declaration

A a();

was changed to:

A a;

because the compiler tried to recognize the parenthesis as an operator, which doesn't exist. The "default" constructor was changed because the linker did not recognize that the symbol had been used. You can override this behavior by programming in a base class which utilizes the data field in it's constructor.

kwierman
  • 441
  • 4
  • 11
  • 2
    The compiler didn't think it was an *operator*, it parsed it as a function declaration taking no arguments and returning the type `A`. – David G Jan 24 '14 at 19:08