Reputation: 144
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
Upvotes: 0
Views: 2075
Reputation: 471
In derived class, protected member of base class works as public in derived class.
That is not true. Either your source is wrong, or this quote is taken out of relevant context.
Protected members of publicly-inherited base class are, by default, still protected in the derived class, meaning, the derived class member functions can access them, but they are not accessible from outside of the class.
You can confirm it and learn more details here, specifically in the "Protected member access" paragraph.
Upvotes: 3
Reputation: 72271
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);
}
};
Upvotes: 5