0
votes

I have a class called Foo that has another class called Bar as a field. Bar only has a constructor with arguments. How do I choose the constructor with arguments for Bar (without storing a Bar* instead of Bar, and calling new)?

Foo.h

class Foo
{
    private:
        Bar bar;
};

Bar.h

class Bar
{
    public:
        Bar(int arbitraryArg);
};

Foo.cpp

Foo::Foo()
  : bar(bar(1))
{}

I want to do the above because I hear that it is generally not good to store pointers as fields unless absolutely necessary to avoid managing memory, so I want to avoid something like this:

Foo.h

class Foo
{
    private:
        Bar* bar;

    public:
        Foo();
}

Foo.cpp

Foo::Foo()
  : bar(NULL)
{
    bar = new Bar(1);
}
2

2 Answers

2
votes

So close.

Foo::Foo()
  : bar(1)
{}

You'll also need to declare the constructor Foo() in the class Foo's definition (and all of your class definitions need a ; at the end).

1
votes

What you have looks almost good - but you need to call the constructor, not the argument or variable name.

Change to:

:bar(Bar(1)) {

Note the capital B.