开发者

Polymorphism: Accessing inherited class variable

开发者 https://www.devze.com 2023-01-04 18:05 出处:网络
I have a class that is inherited from an abstract base class. class CStateBase { friend class CApplication;

I have a class that is inherited from an abstract base class.

class CStateBase
{
  friend class CApplication;
  friend class CGraphics;
  virtual int Update() =0;
};

class CStateTitle: private CStateBase
{
  friend class CApplication;
  friend class CGraphics;
  CApplication *f_App;

  int m_iR;

  int Update();

  CStateTitle(CApplication *App);
  ~CStateTitle();
};

In a method of another class, CStateTitle is dynamically allocated into a CStateBase pointer. However, if I use that pointer to try and access the variable int m_iR, the compiler looks for the variable in CStateBase and therefore makes an error. If I could declare virtual int m_iR in the base cl开发者_如何学Pythonass I would think it would work fine, but for some reason it's not letting me declare virtual data members. What is the recommended way to get around this problem? Thanks for any help.


You should inherit publicly from the base class:

class CStateTitle: public CStateBase

otherwise CStateTitle is not a CStateBase from the compiler's point of view, thus you can't polymorphically access CStateTitle objects via a CStateBase pointer.

You can't have virtual data members, only virtual methods in C++. So a workaround could be to declare virtual accessor method(s) for your data member.


The best way is to abstract the access of m_iR into some virtual function.

Another choice would be to move m_iR from CStateTitle into CStateBase. This only makes sense if every class needs an m_iR.

A last resort would be to do a dynamic cast:

CStateBase *csb = ...;

CStateTitle *cst = dynamic_cast<CStateTitle *>(csb);
if (cst)
{
    // have a valid CStateTitle
}
else
{
    // csb is not pointing at a CStateTitle, do whatever is appropriate
}


Since you are trying to access a derived class's member directly from a base class pointer, you are obviously not invoking polymorphism. Therefore you can use dynamic_cast to access that member.

Unsolicited advice: Don't access member variables directly. Think about your hierarchy and how the operation you're trying to accomplish can be accessed using some kind of consistent interface using a virtual method.


You can't have virtual member variables.

You can change when you cast:

CStateTitle *a = new CStateTitle();
a->m_iR = 1;
CStateBase *b = a;

or re cast sometime later using RTTI

CStateBase *a = new CStateTitle();
CStateTitle *b = dynamic_cast<CStateTitle*>(a);
if( NULL != b )
  b->m_iR = 1;

or add a virtual setter method on the base class if all CStateBase where going to have some int that needed to be set.


You can either define a virtual function in the base class to perform the required acccess (getter and/or setter), or, you will have to cast your base pointer to a derived* and continue from there.

0

精彩评论

暂无评论...
验证码 换一张
取 消