0

The question title might not be perfectly clear.

From c++11 on it is possible to declare and initialize class members like int something = 42; in the code below.

On the other hand it's not possible to call a constructor like Foo foo(2) in the example below.

class Foo
{
  int something = 42;
  int value;
public:
  Foo(int ivalue) { value = ivalue; }  // do stuff with value
};

class Bar
{
  Foo foo(2);        // <<< does not compile
  int thisisok = 2;  // this is OK
public:
  // ...
};

class BarOK
{
  Foo foo;

public:
  BarOK() : foo(2)  // OK
  { }
};

Is there any reason why this is would not be possible (maybe in future c++ standards)?

Or is the case I present here too simplistic.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 4
    The syntax is `Foo foo{2};` and exists since C++11 – UnholySheep Nov 30 '21 at 11:19
  • @UnholySheep feeling stupid... thanks. But I'm still wondering why the syntax with `()` like `Foo foo(2);` is not accepted. – Jabberwocky Nov 30 '21 at 11:21
  • 2
    @Jabberwocky The `()` is not accepted because it could create ambiguity with function declaration, the same way some variable declaration actually declares functions and not variables. – Holt Nov 30 '21 at 11:21
  • @chris why should it not be a dupe? I'm tempted to close the question myself as a dupe.. – Jabberwocky Nov 30 '21 at 11:24
  • As far as I could tell, you were trying to accomplish calling a constructor, in which case curly braces or `Foo foo = Foo(2);` work fine (even better since C++17). The question I linked is specifically about why parentheses don't work. That said, I don't claim to know your question better than you do. (The note wasn't aimed at you, but intended to avoid rushing a close vote.) – chris Nov 30 '21 at 11:26

0 Answers0