Class object member of another class

Jan 17, 2011 at 8:26pm
I have a fairly simple class, and I want objects of another class to be private members of that class, and objects of that class are initialized with a value through its constructor like so:

1
2
3
4
5
6
7
8
9
10
class MyClass {
public:
  //whatever code...
private:
  OtherClass objectA("Metallon", 10);
};

//Constructor of OtherClass
OtherClass::OtherClass(std::string aString, int anInt)
:myString(aString), myInt(anInt) {}


The four errors I get are actually two errors repeated twice: "error:expected identifier before string constant" and "expected ',' or '...' before string constant".

What am I doing wrong?
Jan 17, 2011 at 8:29pm
Don't call the constructor inside of the MyClass definition. Use an initializer list inside MyClass's default constructor.
Jan 17, 2011 at 8:29pm
You need to initialize objectA in the member initialization list of MyClass's constructors, not inline as you have done on line 5.
Jan 17, 2011 at 8:38pm
Alright, that works, and actually makes more sense. Is it just how it is? You can't call constructors inside a class declaration?

PanGalactic: you mention an initialization list. If I wanted to create multiple objects with MyClass's default constructor, wouldn't it be fine to do this:
1
2
3
MyClass::MyClass() {
  OtherClass objectA("Hello", 1), objectB("World", 2);
}
Jan 17, 2011 at 8:40pm
No because the objectA inside of MyClass has already been constructed at that point. If anything, you would just be creating a local variable that hides the objectA in the class.
Jan 17, 2011 at 8:43pm
Could you show me an example, please?
Jan 17, 2011 at 8:44pm
Like this?
1
2
MyClass::MyClass() : objectA("Hello", 1), objectB("World", 2) {
}

You already seemed to be using initializer lists in OtherClass. It's the same thing.
Jan 17, 2011 at 8:47pm
So I just put objectA, objectB etc. in the MyClass private members' part? And then do like what you showed me there?

Wait... ok haha I get it. You create the objects once, and then initialize it. Because that's what a constructor would do, initialize its members. I know this. Wow, a little embarassing, but yes, you're right.

Thank you for your help! =)
Topic archived. No new replies allowed.