-1

In a class, if I have:

private:
   MyClass myObj;

vs

private:
   MyClass myObj();
private:
   MyClass myObj{};

And assuming MyClass takes no parameter in its constructor.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
user1008636
  • 2,989
  • 11
  • 31
  • 45
  • 2
    See e.g. https://en.cppreference.com/w/cpp/language/initialization and https://en.cppreference.com/w/cpp/language/default_initialization – Bob__ Oct 02 '22 at 20:59
  • 3
    [The nightmare of initialization in c++](https://www.youtube.com/watch?v=7DTlWPgX6zs) This runs through all the issues in more detail that you can almost stand. – doug Oct 02 '22 at 20:59
  • Brace initialization is immune to the infamous most vexing parse in C++. Also it's recommended in many guidelines over parentheses initialization. It's also safer in some scenarios. However for the types that have constructors with a `std:: initializer_list` as a parameter, it can cause issues. You should be careful in those situations and use parentheses initialization in those cases. One common example is the STL vector. – digito_evo Oct 02 '22 at 21:49
  • Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to *"search and then research"* and you'll find plenty of related SO posts for this. Moreover, this is explained in any beginner [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Here are some dupes: [dupe1](https://stackoverflow.com/questions/71806191/how-to-create-an-object-in-a-form-like-this-ifstream-in) and [dupe2](https://stackoverflow.com/questions/18222926/what-are-the-advantages-of-list-initialization-using-curly-braces) – Jason Oct 03 '22 at 09:04

1 Answers1

4
MyClass myObj;

This declares a class member named myObj, that gets default-constructed, by default.

MyClass myObj();

This declares a class method, a class function, named myObj that takes no parameters and returns a MyClass object.

MyClass myObj{};

This also declares a class member named myObj, that gets default-constructed, by default, just like without the {}.

Welcome to C++.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148