: You are totally right!
:
: The code I suggested does not call the copy constructor:
: : :
: : : MyClass a;
: : : MyClass b;
: : : b = a;
: : :
:
: But code like this will:
:
: MyClass a;
: MyClass b = a;
:
:
: I pasted the code below if you want to check it:
:
:
: #include <iostream>
:
: //The Gossip class I use from www.codepedia.com/1/CppGossip
: struct Gossip
: {
: Gossip(const Gossip& g)
: {
: std::cout << "Copy constructor" << std::endl;
: }
: Gossip& Gossip::operator= (const Gossip& g)
: {
: if (this == &g)
: {
: std::cout << "Assigment operator: prevented self-assignment" << std::endl;
: return *this;
: }
: std::cout << "Assigment operator" << std::endl;
: return *this;
: }
: };
:
: //I commented the screen output
: //generated by every scope
: int main()
: {
: {
: std::cout << "*** Test 1 ***" << std::endl;
: Gossip a;
: Gossip b = a;
: //Constructor
: //Copy constructor
: //Destructor
: //Destructor
: }
: {
: std::cout << "*** Test 2 ***" << std::endl;
: Gossip a;
: Gossip b;
: a = b;
: //Constructor
: //Constructor
: //Assignment operator
: //Destructor
: //Destructor
: }
: }
:
:
: Test #2 was the one I incorrectly suggested, test #1 does exactly what you requested. Note that it does call the copy constructor even when the assignment operator is defined!
:
: See ya,
: bilderbikkel
:
:
The original question was
"In what situation, compiler checks first for assignment operator, if it is not implemented then checks for copy constructor and calls copy constructor?"
In your first example it will not check for the assignment operator, it will go straight for the copy constructor. Note that these two rows have exactly the same meaning:
MyClass x(y); // copy constr
MyClass x=y; // copy constr
If you removed the assignment operator in your second example, it wouldn't run the copy constructor - it would run the default assignment operator, meaning that it would copy all the data from y to x (and all possible pointers in y will be pointing at the wrong location).
Sidenote: A general rule is that if your class needs to implement a copy constructor, the assignment operator or a destructor, it will need to implement all 3 of them.
As for the OP's question, I can't think of any such situation.