In 13-1, Rectangle
and Triangle
do not have access to Shape
's private members and we have to use access functions get_x()
, get_y()
, get_color()
. This makes our program quite messy. On one hand, a derived class do not have access to the private members of its base class, which makes programming cumbersome. On the other hand, granting a derived class access to their private members is not a good idea either (since we can always access the private members of any class by simply inheriting it!) How to solve this problem? Using the protected members.
Shape
by changing its privated data members to protected data members.get_x()
, get_y()
, get_color()
. Keep the constructor Shape(int, int, string)
.output()
in Shape
that simply outputs I'm a shape\n
.
// Do NOT CHANGE main()! You may get penalty points.
int main() {
int x, y;
string str;
cin >> x >> y >> str;
Rectangle rec(x, y, str);
cin >> x >> y >> str;
Triangle tri(x, y, str);
rec.output();
tri.output();
Shape *p = &rec;
p->output();
p = &tri;
p->output();
return 0;
}
10 7 blue
10 5 black
I'm a Rectangle: location_x = 10, location_y = 7, color = blue
I'm a Triangle: location_x = 10 , location_y = 5, color = black
I'm a Shape
I'm a Shape