I need to use default parameters for an inherited class's constructor.
class A
{
public:
A(int data)
{
a_data = data;
}
~A(){}
int a_data;
};
class B : public A
{
public:
B(int in, int num = DATA) : A(num)
{
b_data = in;
}
const int DATA = 9;
int b_data;
};
int main()
{
B b(3);
int x = b.a_data;
return 0;
}
I've found here that I can use a default parameters for a child's class constructor. But it is said that we should use a global parameter.
But I use a data from class "B" so the A constructor is called before this data is released. In the result I get some garbage in "x" but not 9.
! So, the problem was extracted from another, more particular one. I have a basic class "Object". And some children like "Mob" or "Player". Object has a physical (Box2D) object inside. Certanly, all the actions creating that physical body are the same, except of some parametres. So, I store algorythm in "Object" construtor, and put all the needed data in child classes. But, I can't reach this data, before creating an "Object" which requires that data.
Here is an example of the solution for one dependent class.
I would appreciate any help.
cost int num = 9when constructing A?B(int in) : A(num)is called, this is executed beforeconst int num = 9, which is 0 by default. ThusA(num)is always called with 0. Is this a correct interpretation?numis not even0, it is uninitialized. It happens to be zero in some cases, but in general trying to use un-initialized variables is undefined behaviour.