significance/usecase of variable overriding in classes

Is there any significance/use-case of below variable overriding in classes?

have a look of the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

using namespace std;

class ABC
{
    public:
    int a = 10;
};

class XYZ : public ABC
{

    public:
    int a = 20;
};

int main()
{
      XYZ obj;
   
      cout << "XYZ.obj = " <<obj.a<<endl; //value printed is 20, means overriding of variable is there, Is there any significance/usecase of such variable overriding?


   return 0;
}


output:

XYZ.obj = 20

Thanks
Amit
It's not really "overriding" the variable. The object contains both variables. The variable defined in XYZ overshadows the variable with the same name in ABC. You can still access both variables if you explicitly specify which class you want to read the variable from.

1
2
3
cout << "obj.a      = " << obj.a << endl;      // 20
cout << "obj.XYZ::a = " << obj.XYZ::a << endl; // 20 (same as above)
cout << "obj.ABC::a = " << obj.ABC::a << endl; // 10 

I don't think it's useful for anything. It's more like something you should try to avoid.
Last edited on
thanks Peter87
Topic archived. No new replies allowed.