0

I'm trying to neatly create a objects within a class and I've run into what seems to me to be an odd limitation in c++, and I wondered if I'm just missing a syntax trick or whether it's truly impossible; specifically it seems like I cannot explicitly instantiate a class object inside another class if the constructor of the former has parameters (the parameters are constant) generating the odd message: 'Expected parameter declarator'

It seems as though only default constructors are supported in this scenario, or am I missing a bit of magic?

Currently using c++17 (simply because that's the default in this IDE)

class Fred
{
public:
    Fred(const int i)
    {
    }
    
    Fred()
    {
    }
};

Fred fred1(0);          // This compiles

class Charlie
{
    Fred fred2();       // This compiles
    Fred fred3(0);      // This does not compile
};
MushyTeas
  • 1
  • 1
  • Note that `fred2` is a function. You want `Fred fred2;`. or `Fred fred2{};`. – HolyBlackCat Jun 08 '22 at 06:44
  • `Fred fred2();` is a member function declaration, not a data member declaration. Parentheses are not allowed as data member initializer, see duplicate. – user17732522 Jun 08 '22 at 06:44
  • Ah, yes, apologies... I shouldn't have put those brackets on fred2. - But in regards to fred3... the only way is `Fred fred3 = Fred(0);` I guess? – MushyTeas Jun 08 '22 at 06:58
  • @MushyTeas `Fred fred3{0};` also works. Which one to chose is mostly a matter of style (except if `Fred` has `std::initializer_list` constructors). – user17732522 Jun 08 '22 at 12:11

0 Answers0