0

When I want t put initial values inside the class definition there are two ways it can be done: with {} and =

class A
{
public:
   int a = 1;
   bool b = false;
   someClass* obj = nullptr;
};

class B
{
public:
   int a {1};
   bool b {false};
   someClass* obj {nullptr};
};

Is there any difference between those two options? Will in class A and B be something different in a way fields where initialized?

With = it will be copy initialization, so with {} should be more efficient? Or in case of in-class initialization they are equal and just provide different syntax?

Bruice
  • 63
  • 6
  • 4
    There are some nuanced differences. If you have an hour to kill, here's a fairly comprehensive presentation that covers those differences [The Nightmare of Initialization in C++](https://www.youtube.com/watch?v=7DTlWPgX6zs) by Nicolai Josuttis at CppCon 2018. For instance, change both `1` to `1.0` and see the difference in what the compiler does. (I don't remember all the nuances off the top of my head, otherwise I'd take a stab at answering.) You might want the `language-lawyer` tag, if you want chapter-and-verse... but it's a simple question with a BIG answer. – Eljay Jul 27 '21 at 16:38
  • There may be more or better duplicate targets - feel free to edit the list (if you have a hammer) or ping me with suggestions (if you don't). – Adrian Mole Jul 27 '21 at 18:23

0 Answers0