0

I have something that looks like this:

class Foo
{
    public:
        Foo(parameter);
}

class Bar
{
    Foo fooObject;
}

Bar::fooObject(data);

But I get:

error: expected constructor, destructor, or type conversion before '(' token

So my question is: how do I construct fooObject from outside Bar?

  • 1
    It needs to be static, and the definition needs a type. – Dan Aug 03 '17 at 11:47
  • 5
    You don't. Why are you trying to? – molbdnilo Aug 03 '17 at 11:48
  • 3
    Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Aug 03 '17 at 11:52
  • I agree with @Dan. You seem to try to define (in contrast to declare) a member of a class outside of the declaration of the class. This means it is only associated to the class, but not with an instance of the class. This in turn seems to imply that you want a static class member, i.e. which has always the same value, no matter from which instance (or even without an instance) it is accessed. If that is what you want, you need to declare it static and define it (probably in a separate .cpp file) with a type before the `Bar::`. I.e. `Foo Bar::fooObject(data);` with "data" of type "parameter". – Yunnosch Aug 03 '17 at 12:02
  • Thank you! I forgot to mention that the parameter for Foo can be the same across all Bar instances. – Daniel Wærness Aug 03 '17 at 12:06

2 Answers2

1

You can have a constructor that take an instance of Foo from outside of class and then you can copy or move that instance to your member variable. Another approach would be to take required parameters to construct an instance of Foo and then use member initializer list to construct member variable.

class Bar
{
public:
   Bar(const Foo& foo) // Copy
      : fooObject(foo)
   {
   }

   Bar(Foo&& foo) // Move
      : fooObject(std::move(foo))
   {
   }

   Bar(int example)
      : fooObject(example)
   {
   }

private:
   Foo fooObject;
}
MRB
  • 3,752
  • 4
  • 30
  • 44
1

Initialize members using a constructor and member initializer list:

class Foo{
public:
    Foo(int x);
};

class Bar{
public:
    Bar(int param);
private:
    Foo fooObject;
};

Bar::Bar(int param) : fooObject(param){};

If by outside of the class you mean the class member function definition then you would use the following syntax that goes into a source (.cpp) file:

Bar::Bar(int param) : fooObject(param){};  // ctor definition outside the class

The declarations can be placed in a header file.

Ron
  • 14,674
  • 4
  • 34
  • 47