Reputation: 691
Given the code below, we can access private data of base class if the function in base are protected by using inheritance. My question is, is there any way we can access private data if all methods in base class are also set to private?
class Base
{
int i;
protected:
void set(int data){
i = data;
}
int get(){
return i;
}
};
class derive: Base{
public:
void change(int x){
set(x);
cout<<get()<<endl;
}
};
int main()
{
derive b;
b.change(3);
return 0;
}
Upvotes: 0
Views: 553
Reputation: 41
By using friend
Making the derive class the friend of Base
class derive;//forward declaration
class Base
{
int i;
private:
void set(int data){
i = data;
}
protected:
int get(){
return i;
}
public:
friend class derive;
};
class derive : public Base{
public:
void change(int x){
set(x);
cout<<get()<<endl;
}
};
You should be aware of public/protected inheritance. class a : public/protected b
Do not use access specifier overloading/overriding:
Now I show how to redeclare the access specifier of an inherited member:
class derive : public Base{
public:
Base::set;//this is valid redeclaration within public scope. Now anybody could use derive::set(x)
void change(int x){
set(x);
cout<<get()<<endl;
}
}
Upvotes: 0
Reputation: 817
Setting the members to private in the base class will make it private for all children as well. You can define new public functions to change these members in the children.
Upvotes: 0
Reputation: 6339
"we can access private data of base class if the function in base are protected by using inheritance", no you're not really accessing private data. You're invoking a setter in the base class that does it for you. And no you won't be able to call the private methods of your base class.
Upvotes: 2