Search code examples
c++copy-constructorassignment-operator

Constructor or Assignment Operator


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?


Solution

  • What is happening here depends a bit on your compiler. It could create a temporary object using the int constructor and then copy construct b from that temporary. It will most likely elide the copy constructor call however. In neither case will the assignment operator be used.