class parent{
private:
constint num1;
constfloat num2;
public:
virtualint get_num1()=0;
virtualfloat get_num2()=0;
};
class child_1 : public parent{
public:
int get_num1();
float get_num2();
child_1();
};
class child_2 : public parent{
public:
int get_num1();
float get_num2();
child_2();
};
How do I initialize the parameters num1 and num2 of the parent class ( which are inherited by the children classes ) from the constructor of the children classes. I get an error because num1 and num2 are not part of the definition of child_1 and child_2. Any ideas other then removing these field from the parent and placing them in the children
Choose one.
1) Add set methods to parent (and by the way, having virtual gets seems a bit pointless in this case).
2) Write a constructor for parent that sets the two and then call it from child's ctor.
3) make num1 and num2 protected (or public) so that children have access to them.
class parent{
publicconstint num1;
constfloat num2;
virtualint get_num3()=0;
virtualfloat get_num4()=0;
};
class child_1 : public parent{
public:
int get_num3();
float get_num4();
child_1(int,float);
};
class child_2 : public parent{
public:
int get_num3();
float get_num4();
child_2(int,float);
};
child_1::child_1(int p1, float p2) : num1(p1), num2(p2) {}
child_2::child_2(int p1, float p2) : num1(p1), num2(p2) {}
I get an error saying that there is no constructor for parent to initialize num1 and num2. I cant have a constructor here since its an abstract class.
Set methods is an option, but I would really like num1 and num2 to be const . I cant do that if I have to use set methods to initialize their values
I also get an error saying that num1 and num2 are "not non-static data members or base class" of class child_1 and child_2, even though they are "public" in the base class.
Sorry for the mistake earlier, but any suggestions?
There is nothing wrong with an abstract class having a constructor, as far as I know..
Add this to parent: parent(int n, float m) : num1(n), num2(m){}
Make child constructors like this: child_1::child_1(int p1, float p2) : parent(p1, p2) {}
That should work.
Awesome that worked!! Thanks hamsterman, for that solution.
For some reason I thought it would be invalid for an abstract base class to have a constructor, so didnt bother trying this method.