2

I have a simple class with two objects in main(). Are there any differences in the initialization of the constructor ?

//#include <systemd/sd-bus.h> #include <iostream> #include <memory> class Simple { private: int a; public: Simple(int b) : a(b) { } void show() { std::cout << a; } }; int main() { Simple firstObj = Simple(5); firstObj.show(); Simple secondObj(5); secondObj.show(); return 0; } 

2 Answers 2

3
  • Pre-C++17,

    first one uses also copy(Pre-c++11)/move constructor (which might be elided) whereas second uses only Simple(int).

  • Since C++17,

    both are equivalent.

Sign up to request clarification or add additional context in comments.

1 Comment

Your Pre-C++17 description is a Pre-C++11 description. [C++11, C++17) description is same except move constructor would be used.
1

Simple firstObj = Simple(5); performs copy initialization, Simple secondObj(5); performs direct initialization, since C++17 they have the exact same effect: the object is initialized by the constructor Simple::Simple(int) directly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.