1

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?

2 Answers 2

3

Your version with pointers is very close - modify it as follows (see comments below):

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

class Bar {
private:
    Foo f;          // Make f a value, not a pointer
public:
    Bar() : f(5) {} // Initialize f in the initializer list
};
Sign up to request clarification or add additional context in comments.

Comments

1

If you have C++11 support, can initialize f at the point of declaration, but not with round parentheses ():

class Bar {
private:
    Foo f{5}; // note the curly braces
};

Otherwise, you need to use Bar's constructor initialization list.

class Bar {
public:
    Bar() : f(5) {}
private:
    Foo f;
};

1 Comment

Great, thanks! I see how this works now, and it helps me better understand when values are initialized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.