class CStateBase
{
friendclass CApplication;
friendclass CGraphics;
virtualint Update() =0;
};
class CStateTitle: private CStateBase
{
friendclass CApplication;
friendclass 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 virtualint m_iR in the base class 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.
This looks to me like a misunderstanding of polymorphism (and an abuse of friendship - it kind of defeats the point of making variables private if every class that interacts with this one is a friend). I think there are more general design issues that should be explained here.
But I'm at work and don't have time to write a long post! Maybe when I get home.
When you use an "is-a" relationship, ie, use a base class pointer to store a child class pointer, the compiler just identifies it as a Base class type pointer and checks the base class object for your variable and it fails to find that variable. So you need to have this member variable declared in base class for normal use.
However your class is a polymorphic class and even though its a private inheritance you are using inside a friend class, you can use dynamic cast and can access the variable.
I won't comment on your design, as I don't know what these classes are supposed to do, but if you want to access m_iR from a CStateBase pointer, I guess you could define a virtual function that grants you access to it, like this:
Getters that return a reference are totally pointless. If you're doing that you might as well just make m_iR a member of CStateBase. Same effect, less overhead, and it doesn't demand you reimplement get_iR() in every class which derives from CStateBase like you would if it was pure virtual.
Although this design has bigger issues.
-) Abuse of friendship.
-) 'CGraphics' probably shouldn't be accessing these classes. It likely should be the other way around
-) You probably want public inheritance, not private
I would comment on solutions to the above, but I'm pretty certain the OP disappeared from this thread and won't return.