Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access parent class's data member from child class, when both parent and child have the same name for the dat member

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.

like image 631
codeLover Avatar asked Jul 17 '12 15:07

codeLover


People also ask

How do you access parent members in the child class?

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.

Can a parent class access child class variables?

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.

Can child class hold the reference of parent class in Java?

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.

Can a parent class object call child method?

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.


2 Answers

Almost got it:

this->x = Parent::x;

this is a pointer.

like image 170
Luchian Grigore Avatar answered Oct 15 '22 02:10

Luchian Grigore


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.

like image 35
Chad Avatar answered Oct 15 '22 02:10

Chad