Robert Atkins
Robert Atkins

Reputation: 24718

Calling a constructor with no parameters works, with a parameter doesn't. Why?

I have a class defined as follows:

class Foo {

  private:
    boolean feature;

  public:
    Foo(boolean feature) : feature(feature) {}

  // ...
};

I'm trying to construct an instance, as a private property of another class:

class Bar {

  private:
    Foo foo(true);

    // ...
  };

This doesn't work. I get expected identifier before numeric constant on the line with the declaration. When I remove the parameter from Foo's constructor definition simply and ask for a Foo foo;, it works.

Why?

How do I define and declare an instance of Foo that takes a boolean parameter?

Upvotes: 0

Views: 113

Answers (2)

nwp
nwp

Reputation: 10011

The pre-C++11 way to do this is:

class Bar {
  public:
    Bar() : foo(true){} //initialization
  private:
    Foo foo; //no parameter
};

Bonus:

class Bar {
  private:
    Foo foo(); //<- This is a function declaration for a function
               //named foo that takes no parameters returning a Foo.
               //There is no Foo object declared here!
};

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254741

You can't use that initialisation syntax in a class member declaration; you can only initialise members with {} or =. The following should work (assuming support for C++11 or later):

Foo foo{true};
Foo foo = Foo(true);

Upvotes: 8

Related Questions