si***************@gmail.com wrote:
How come I an not use class initialization to initalize inherited
attributes?
i have this code:
B::B(A& a) {
x = a.x;
y = a.y;
}
class A {
public:
int x;
int y;
};
class B: public A{
public:
B(A& a);
};
and I get this compile error:
B.cpp:34: error: class 'B' does not have any field named 'x'
Bc.pp:35: error: class 'B' does not have any field named 'y'
can someone please tell me why?
Probably the order of the code, the following works fine:
class A {
public:
int x;
int y;
};
class B: public A{
public:
B(A& a);
};
B::B(A& a) {
x = a.x;
y = a.y;
}
int main() {
}
It's probably preferable to make x and y private and provide a
constructor for A, with an initialisation list, and then provide an
initialisation list for B (I've also provided another constructor for B):
class A {
public:
A(int x, int y) : x_(x), y_(y) {};
private:
int x_;
int y_;
};
class B: public A {
public:
B(int x, int y) : A(x, y) {}
B(A& a) : A(a) {};
};
int main() {
}
I hope that gives you an idea.
That way, you have kept encapsulation. (Only A can play with it's
privates, B cannot).
Ben Pope
--
I'm not just a number. To many, I'm known as a string...