简体   繁体   中英

C++ | Reusing protected member of the Base class

Suppose I have a Base & Derived class:

class Base{
 private:
  int* _privateIntPtrB;
 protected:
  int* _protectedIntPtrB;
 public:
  //methods which use
  //_privateIntPtrB and _protectedIntPtrB

class Derived: public Base{
 private:
  int* _privateIntPtrD;
 protected:
  int* _protectedIntPtrB; //I am redeclaring this var
 public:
  //methods which use
  //_privateIntPtrD and _protectedIntPtrB

My question: In the methods of the Derived class, does the Derived version of _protectedIntPtrB get used? (I think it does, but want to confirm).

If a method is not redefined by the Derived class, which version of the _protectedIntPtrB will be used by a pointer to Derived class?

The reason I am asking - I want to initialize _protectedIntPtrB in the Derived class differently and want that version of the _protectedIntPtrB to be used in all the instances of Derived class.

In the methods of the Derived class, does the Derived version of _protectedIntPtrB get used?

Yes, it hides the base class member and so an unqualified use of _protectedIntPtrB in the scope of Derived refers to Derived::_protectedIntPtrB . (The base class variable is still available, if qualified as Base::_protectedIntPtrB ).

If a method is not redefined by the Derived class, which version of the _protectedIntPtrB will be used by a pointer to Derived class?

The base-class variable. Data members of derived classes are not available from the base class.

The reason I am asking - I want to initialize _protectedIntPtrB in the Derived class differently and want that version of the _protectedIntPtrB to be used in all the instances of Derived class.

Usually, the best way to make derived classes behave differently to their base classes is by overriding virtual functions. It would probably be better if you had a think about exactly what you want to achieve: work out what behaviour you want to modify, and encapsulate that in a virtual function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM