I have a problem. I want some class B to create a data member of another class A. The default constructor of A is protected, so I take another constructor.
A a(8,3);
The compiler however thinks that a is a function declaration and gives an error message on its parameters. So how can I tell the compiler that a is a data member?
This exact same thing happened to me. You can't use constructors in a class like that. You need to initialize the object with the main class constructor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
struct ClassA
{
int A, B;
ClassA(){}
ClassA(int a, int b){ A = a; B = b; }
};
struct ClassB
{
ClassA MyObjA(1, 2); //Illegal, you can't use a constructor in a declaration
ClassA MyObjB; //Legal, but to initialize it you have to do so in ClassB's constructor
ClassB(){ MyObjB.A = 1; MyObjB.B = 2; }
};
The constructor of B is where the constructors of members of B are chosen, instead of in the class description. Good point, hamsterman. I only knew that you can choose the constructor of the parent of B there.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
struct ClassA
{
int A, B;
ClassA(){}
ClassA(int a, int b){ A = a; B = b; }
};
struct ClassB : ClassA
{
ClassA MyObjA;
ClassA MyObjB;
ClassB();
}
ClassB::ClassB() : ClassA(2,3), MyObjA(5, 7), MyObjB(3, -2){};
Maybe, you also know how to choose another constructor when using new[], but it might be that you are really condemned to the default constructor with new[].