Suppose I have a class Foo whose constructor has a required argument. And further suppose that I'd like to define another class Bar which has as a member an object of type Foo:
class Foo {
private:
int x;
public:
Foo(int x) : x(x) {};
};
class Bar {
private:
Foo f(5);
};
Compiling this will give errors (in this exact case, g++ gives "error: expected identifier before numeric constant"). For one, Foo f(5); looks like a function definition to the compiler, but I actually want f to be an instance of Foo initialized with the value 5. I could solve the issue using pointers:
class Foo {
private:
int x;
public:
Foo(int x) : x(x) {};
};
class Bar {
private:
Foo* f;
public:
Bar() { f = new Foo(5); }
};
But is there a way around using pointers?