13783 - EE2310_Lab_13_2   

Description

Protected Members & Static Binding

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.

What You Need to Do

  1. Modify the class Shape by changing its privated data members to protected data members.
  2. We can remove all 3 member functions get_x(), get_y(), get_color(). Keep the constructor Shape(int, int, string).
  3. Define another member function output() in Shape that simply outputs I'm a shape\n.
  4. The main function is given as follows. Do not change it.
// 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;
}

Input

10 7 blue
10 5 black

Output

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

Sample Input  Download

Sample Output  Download

Tags




Discuss