0

What advantages do we have when inheriting from a class whose attributes are protected rather than private?

23rd Oct 2016, 6:18 PM
Venus
Venus - avatar
5 ответов
+ 2
the advantage is that you can use the (this->) pointer to modify your variables in the derived classes, if you have variables in private you must use methods to see and change their value. a little example. class father { protected: int num; public: int get_num() const { return this->num; } void set_num(int n) { this->num = n; } }; class son: public father { public: void addition_to_num(int n) { this->num += n; cout << this->num; /*if num is private you must use*/ int x; x = get_num() + n; set_num(x); cout << get_num(); /*you cant use the this-> pointer and must use methods to see and change the value of num*/ } };
23rd Oct 2016, 7:38 PM
Hector Sulbaran
Hector Sulbaran - avatar
+ 1
Shouldn't it be this, if the attributes are private then its inaccessible to the derived class whereas if we have protected attributes then the protected members of the base class becomes protected members of the derived class.
24th Oct 2016, 3:38 AM
Venus
Venus - avatar
0
private means 'don't ever mess with my stuff' (unless you are a friend). Protected is useful for data or helper functions that you don't want everybody to be able to access, but a derived class may need. Consider a member function 'update()' that updates some internal state of you class' object. You don't want the user of your class to call update() directly, as you have constraints on when an update() even makes sense. However, your derived class may need to update the state of it's base class, hence 'protected'.
23rd Oct 2016, 6:44 PM
Ullrich Franke
Ullrich Franke - avatar
0
if the base class is declared as privite then its member functions are not inherited by the derived class..if the base class is declared as protected member fuctions declared as private and protected in base class remains same in derived class..whereas the public data members become protected in derived class.
25th Oct 2016, 2:46 AM
Gowtham
Gowtham - avatar
0
Everything to do with inheritance becomes simple when you consider the one fundamental rule of thumb: "There's no point inheriting private members of a class, purely for the private members" Its moronic
25th Oct 2016, 8:48 PM
Lucas Barbosa
Lucas Barbosa - avatar