How to access a parent class data member from a child class when both parents and child have the same name for the dat member

my script is as follows:

class Parent
{
public:
int x;
}

class Child:public Parent
{
int x; // Same name as Parent "x".

void Func()
{
   this.x = Parent::x;  // HOW should I access Parents "x".  
}
}

Here's how to access the parent "X" from the Child member function.

+5
source share
3 answers

It almost happened:

this->x = Parent::x;

this is a pointer.

+9
source

Access to it through the scope resolution operator will work:

x = Parent::x;

, . , "is-a". , , , / , "is-a" . , , , , , . , , , .

+3

This is just a brief explanation of the solutions provided by Lucian Grigor and Mr. Anubis, so if you are interested in how this works, you should read it further.

C ++ provides the so-called "scope operator" ( ::), which is great for your task.

More information is available on this page . You can combine this statement with the class name ( Parent) to access the parent variable x.

0
source

All Articles