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".
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:
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.
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.