0

1. If I instantiate objects like this, no error occurs.

class A {};

int main () {
    A a = A ();
    A &b = a;
    return 0;
} 

2. If I instantiate object this way, compiler reports error C2440: 'initializing' : cannot convert from 'A (__cdecl \*)(void)' to 'A &' when a's reference is copied to b.

class A {
};

int main () {
    A a();
    A &b = a;
    return 0;
}

3. But if I add a constructor with parameters and pass in some argument(s) to this ctor during instantiation in the second way, there is no error!

class A {
public:
    A (int a) {}
};

int main () {
    A a(5);
    A &b = a;
    return 0;
}

Can anyone please explain this?

matsjoyce
  • 5,744
  • 6
  • 31
  • 38

2 Answers2

1

In the second example, the compiler thinks that A a(); is a function returning A called a, that takes no parameters.

error C2440: 'initializing' : cannot convert from 'A (__cdecl *)(void)' to 'A & says that the compiler doesn't know how to convert a function returning A taking no parameters (void) to a reference of type A.

lcs
  • 4,227
  • 17
  • 36
1

When you create object "a" of class "A" and you want call the constructor without parameters you mustn't write "A a();", but simply "A a;". I used to make that mistake from time to time as well. The standard constructor is automatically called.

avrFreak
  • 9
  • 1
  • Sorry, made a mistake while typing. Don't write A a (). You have to leave the brakets away. Sorry again, my fault. – avrFreak Oct 21 '14 at 19:25