What the difference between A a1(5); and A a2 = A(5) ? Both of the works, but I really want know the difference between them, because I used method 2 in one of my project and I suffered from a bug which is fixed after I change to method 1. Thanks in advance!
class A {
public:
int val;
A() : val(0) {}
A(int newVal) : val(newVal) {}
};
int main()
{
A a1(5); // method 1
A a2 = A(5); // method 2
}
The first one is called direct initialization, the second one is called copy-initialization.
The second one will NOT compile if you make the copy-constructor inaccessible or/and don’t define it as:
Now the second one will not compile. Note that it will not compile in both cases:
privateorprotected).