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

天大地大妈咪最大 提交于 2019-12-04 01:59:14

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.

It's only a brief explaination of solutions provided by Luchian Grigore and Mr. Anubis, so if you are curious 'how this works', you should read it further.

C++ provides a so-called, "scope operator" (::), which is perfectly suited to your task.

More details are provided at this page. You can combine this operator with class name (Parent) to access parent's x variable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!