Is this possible to make parent class member variable to be visible ONLY to immediate child and not further in inheritance hierarchy?
virtual class parent;
string s;
// ..
endclass
class child extends parent;
// s is accessible here
endclass
class grand-child extends child;
// s is NOT accessible here
endclass
In reply to bhupeshpaliwal:
It’s not possible. By default all the variables are public until they are encapsulated using identifiers like “local” or “protected”. If declared string s as protected then all the subclasses will be able to access it.
In reply to bdreku:
I need to ensure ONLY IMMEDIATE child is able to access i.e. grand child should not able to access string s. With private/protected I am not able to achieve the same as shown below:
// Case 1: private qualifier
virtual class parent;
private string s;
// ..
endclass
class child extends parent;
// s is NOT accessible here
endclass
class grand-child extends child;
// s is NOT accessible here
endclass
// Case 2: protected qualifier
virtual class parent;
protected string s;
// ..
endclass
class child extends parent;
// s is accessible here
endclass
class grand-child extends child;
// s is accessible here
endclass
If you wanna the class child class to have restricted access to the variable s then you could declare it as private only in the child class removing the need to have it in the parent. Other way could be using a function to access that variable which encapsulate some sort of restricted access like looking for the parent class if not the main starting parent class then 100% is not the child. Hope i got the question. Regards
I tried some experiments in order to break the inheritance unfortunately is not quite obvious IMO since the inheritance is still hard to break. anyway still not able to get the valid use cases honestly even if we extend from the child class you can still cast them in order to make them compatible to the parent class.
the structure is generally speaking this one:
parent
2. child
[list=1]
3. g-child
[/list]
going from bottom to top you are going to find the same parent even if you declare a variable to be local for instance assigned by a function which will check the parent from where the class is derived this approach is still broken since by casting you will still allow the access. Why not simply change the approach since your problem could be fixed in different way simply do not use the same class and derive them. Regards