3

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;
cuong.pq
  • 137
  • 1
  • 1
  • 4
  • 2
    The first one is called [direct initialization](https://en.cppreference.com/w/cpp/language/direct_initialization) while the other is [copy initialization](https://en.cppreference.com/w/cpp/language/copy_initialization). There are subtle differences between them. In your case they will do the same thing. – freakish Jul 27 '20 at 07:03
  • You might need a book. Look at beginner's list of this link https://stackoverflow.com/a/388282/4123703 – Louis Go Jul 27 '20 at 07:04
  • Also this works since `MyNum(int num)` qualifies as [converting constructor](https://en.cppreference.com/w/cpp/language/converting_constructor) because it takes only one parameter andis not marked `explicit`. – Lukas-T Jul 27 '20 at 07:05

1 Answers1

4

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405