Testing program
#include <iostream>
using namespace std;
class A
{public:
A (): I(0) {cout << "default construcot" << endl; };
explicit A (int i): I(i) {cout << "another construcot" << endl; };
A (const A& a): I(a.I) {cout << "copy constructor" << endl; }
A& operator = (const A& a)
{cout << "assignment operator" << endl;
if (this == &a) return *this;
I = a.I;
return *this;
}
void show () {cout << I << endl; };
private:
int I;
};
int main ()
{A a = A(1);
A b;
b = A(2);
a.show();
b.show();
return 0;
}
conclusion
another construcot
default construcot
another construcot
assignment operator
1
2
shows that the object "a", unlike "b", was built from A (1) "directly" without executing the assignment operator. But the copy constructor was not executed either. What for? Is there any way to force the assignment operator in this case? I would expect this behavior if I wrote
A a (1);
but I want
A a = A(1);
which should be different from the first case. Or not?
(Actually, the problem arises when I have a class B derived from A and require the assignment operator to handle the declaration as A a = B (...).)