Search code examples
c++inheritanceradixderived

Can we access protected member functions of base class in derived class?


As i have studied that Derived class can access protected member of base class. In derived class, protected member of base class works as public in derived class. But when i implement this , i get a error

My code :


#include <iostream>
 
using namespace std;

class Shape {
   protected :
      void setWidth(int w) {
         width = w;
      }
      void setHeight(int h) {
         height = h;
      }
      
   protected:
      int width;
      int height;
};

// Derived class
class Rectangle: public Shape {
   public:
      int getArea() { 
         return (width * height); 
      }
};

int main(void) {
   Rectangle Rect;
 
   Rect.setWidth(5);
   Rect.setHeight(7);

   // Print the area of the object.
   cout << "Total area: " << Rect.getArea() << endl;

   return 0;
}

Error :

In function ‘int main()’:
32:19: error: ‘void Shape::setWidth(int)’ is protected within this context
    Rect.setWidth(5);
                   ^

:9:12: note: declared protected here
       void setWidth(int w) {
            ^~~~~~~~
:33:20: error: ‘void Shape::setHeight(int)’ is protected within this context
    Rect.setHeight(7);
                    ^
:12:12: note: declared protected here
       void setHeight(int h) {
            ^~~~~~~~~


Please somebody help me to understand the Access modifiers


Solution

  • Yes, the derived class can access protected members, whether those members are data or functions. But in your code, it's main which is attempting to access setWidth and setHeight, not Rectangle. That's invalid just like using width and height from main would be.

    An example of the derived class using the protected member functions:

    class Rectangle: public Shape {
    public:
        int getArea() const { 
            return (width * height); 
        }
        void setDimensions(int w, int h) {
            setWidth(w);
            setHeight(h);
        }
    };
    

    Or if you really want Rectangle to let anyone else use the functions, you can use the access Rectangle has to make them public members of Rectangle instead of protected:

    class Rectangle: public Shape {
    public:
        using Shape::setWidth;
        using Shape::setHeight;
    
        int getArea() const { 
            return (width * height); 
        }
    };