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

36,439

Solution 1

Almost got it:

this->x = Parent::x;

this is a pointer.

Solution 2

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.

Share:
36,439
codeLover
Author by

codeLover

Coding is my cardio :)

Updated on July 05, 2022

Comments

  • codeLover
    codeLover almost 2 years

    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.