my scenario is as follows::
class Parent
{
public:
int x;
}
class Child:public Parent
{
int x; // Same name as Parent's "x".
void Func()
{
this.x = Parent::x; // HOW should I access Parents "x".
}
}
Here how to access Parent's "X" from a member function of Child.
Accessing Parent Class Functions But have you ever wondered how to access the parent's class methods? This is really simple, you just have to call the constructor of parent class inside the constructor of child class and then the object of a child class can access the methods and attributes of the parent class.
The only unusual aspect is that, within child class method definitions, you can't directly access parent class instance variables. For example, if the parent had a height instance variable, child class method definitions wouldn't be able to access this directly.
The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.
we can called the overridden methods of child class with parent class reference we can not call the direct child class methods from parent class reference.
Almost got it:
this->x = Parent::x;
this
is a pointer.
Accessing it via the scope resolution operator will work:
x = Parent::x;
However, I would question in what circumstances you want to do this. Your example uses public inheritance which models an "is-a" relationship. So, if you have objects that meet this criteria, but have the same members with different values and/or different meanings then this "is-a" relationship is misleading. There may be some fringe circumstances where this is appropriate, but I would state that they are definitely the exceptions to the rule. Whenever you find yourself doing this, think long and hard about why.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With