Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"MyClass mc = MyClass()" or "MyClass mc"?

What is the difference between

MyClass mc = MyClass();

and

MyClass mc;

in C++?

like image 870
Andreas Avatar asked Feb 20 '23 12:02

Andreas


2 Answers

The first invokes copy constructor, with temporary object as parameter - MyClass() creates temporary.

The second invokes default constructor.

In reality, they are, in most cases, optimized out to the same code, but that's the semantical difference.


As Negal mentioned, the case is a bit different with POD types; when "MyClass" is POD, the second snippet will not value-initialize mc, whereas first will.

like image 141
Griwes Avatar answered Feb 22 '23 00:02

Griwes


The first one is copy initialization and the 2nd one is default initialization.

For example, the following code will not compile:

class MyC
{
public:
MyC(){}
private:
MyC(const MyC&) {}
};

int main()
{
  MyC myc = MyC();
  return 0;
}
like image 35
Alexander Chertov Avatar answered Feb 22 '23 00:02

Alexander Chertov