Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 893
Julian Popov Avatar asked May 17 '10 09:05

Julian Popov


People also ask

When copy constructor is called and when assignment operator is called?

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.

What is the difference between the copy constructor and the assignment operator ie when will each of these functions be called and why?

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.

What is the purpose of a copy assignment operator?

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.


1 Answers

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.

like image 63
Konrad Rudolph Avatar answered Sep 28 '22 08:09

Konrad Rudolph