3

I have class called Bar, and in this class Bar there is an object of type Foo (a class). Class Bar takes 3 parameters, x, y and z. Foo takes 2 parameters, y and z.

currently I'm doing this:

class Bar { public: Bar(int x, int y, int z) { foo = new Foo(y, z); do something with x; } private: Foo * foo; }; 

I remember seeing in a book another way to do this using a colon but I don't remember how exactly.

What is the standard or usual way of doing something like this?

3
  • Foo is a container class and contains a vector of type myClass. When I do this I now get the error: 1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\vector(1541): error C2036: 'myClass *' : unknown size It compiled and ran fine when I did it using dynamic allocation. Commented Mar 22, 2013 at 13:44
  • Can you post your actual code? Commented Mar 22, 2013 at 13:48
  • Are you forward-declaring the class? You can do that for pointers and references, but the compiler needs the full definition (read: header) for a plain member. Commented Mar 22, 2013 at 13:50

3 Answers 3

6

Use an initializer list and avoid dynamic allocation:

class Bar { public: Bar(int x, int y, int z) : foo(y, z) {} private: Foo foo; }; 
Sign up to request clarification or add additional context in comments.

Comments

2
class Bar { public: Bar(int x, int y, int z) : foo(y, z) { do something with x; } private: Foo foo; }; 

Comments

0

your perplexing line should be

... Bar(int x, int y, int z) : foo(new Foo(y,z)) { ... private: Foo* foo; ... 

i see other answers dont use pointer. But correct one should be this.

3 Comments

If by "correct" you mean "preserving the unnecessary dynamic allocation and memory leak", then you're right. Personally, I prefer the answers that recommended avoiding dynamic allocation.
I tried to stick to the original question. I saw a pointer type Foo then used a pointer initialization because we dont know the internal structure of Foo. Maybe there are link lists and the user want to do foo = foo->next; in somewhere.Besides it is good to learn preferring non-pointer objects is a common practice.
@FredrickGauss Yes, they're pretty dangerous really. If you want some good info, look up 'RAII'.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.