-3

Their is something I don't understand with OOP : when you have an instance of a class as attribute of another class, how is it possible to instantiate it only in the constructor of the 2nd class?

For example in this example I would like to instantiate the class Foo in Bar's constructor. How should I modify my code so it work?

Foo.h

class Foo
{
private:
    int x, y;

public:
    Foo(int a, int b);
};

Foo.cpp

#include "Foo.h"

Foo::Foo(int a, int b)
{
    x = a;
    y = b;
}

Bar.h

#include "Foo.h"

class Bar
{
private:
    Foo foo;

public:
    Bar();
};

Bar.cpp

#include "Bar.h"

Bar::Bar()
{
}
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

2

Since Foo needs to be constructed from 2 parameters you are either going to have to have the user pass them to Bars constructor and create it with them or just use some hard coded values. I would suggest getting them from the user but also have a default value for the parameters so it acts as a default constructor.

class Bar
{
private:
    Foo foo;

public:
    Bar(int a = 0, int b = 0) : foo(a, b) {}
};
NathanOliver
  • 171,901
  • 28
  • 288
  • 402