What is the difference of () and = in creating class instances?

Viewed 74

I try to create 2 objects of a class like this

#include <iostream> 
using namespace std;

class MyNum
{
private: 
    int m_num;
public:
    MyNum(int num) : m_num{ num }
    {
    }
};

int main()
{
    MyNum one(1);
    MyNum two = 2;
}

What is the difference between these two lines

MyNum one(1);
MyNum two = 2;
1 Answers

MyNum one(1) performs direct initalization, MyNum two = 2; performs copy initialization. They have the same effect here, i.e. initializing the object by the constructor MyNum::MyNum(int).

If you mark the constructor as explicit then the 2nd one becomes ill-formed.

Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.

Related