What is the difference between
MyClass mc = MyClass();
and
MyClass mc;
in C++?
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.
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;
}
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