Can you help me is there definition in C++ standard that describes which one will be called constructor or assignment operator in this case:
#include <iostream>
using namespace std;
class CTest
{
public:
CTest() : m_nTest(0)
{
cout << "Default constructor" << endl;
}
CTest(int a) : m_nTest(a)
{
cout << "Int constructor" << endl;
}
CTest(const CTest& obj)
{
m_nTest = obj.m_nTest;
cout << "Copy constructor" << endl;
}
CTest& operator=(int rhs)
{
m_nTest = rhs;
cout << "Assignment" << endl;
return *this;
}
protected:
int m_nTest;
};
int _tmain(int argc, _TCHAR* argv[])
{
CTest b = 5;
return 0;
}
Or is it just a matter of compiler optimization?
In a simple words, Copy constructor is called when a new object is created from an existing object, as a copy of the existing object. And assignment operator is called when an already initialized object is assigned a new value from another existing object.
The copy constructor initializes the new object with an already existing object. The assignment operator assigns the value of one object to another object both of which are already in existence.
A trivial copy assignment operator makes a copy of the object representation as if by std::memmove. All data types compatible with the C language (POD types) are trivially copy-assignable.
It’s always the default constructor taking an int
that’s called in this case. This is called an implicit conversion and is semantically equivalent to the following code:
CTest b(5);
The assignment operator is never invoked in an initialization. Consider the following case:
CTest b = CTest(5);
Here, we call the constructor (taking an int
) explicitly and then assign the result to b
. But once again, no assignment operator is ever called. Strictly speaking, both cases would call the copy constructor after creating an object of type CTest
. But in fact, the standard actively encourages compilers to optimize the copy constructor call here (§12.8/15) – in practice, modern C++ compilers won’t emit a copycon call here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With