class A {
protected:
virtualvoid render() { /*render stuff*/ }
};
class B: public A {
protected:
A *aInstance;
virtualvoid render() { aInstance->render(); /*render stuff*/ }
};
I feel like subclasses of A should be able to call render() on an A* object, but i'm getting a compiler error in my code. Am I missing something? Is this really not allowed? Do i really need to:
A - make render() public -or-
B - declare subclasses friend classes of A
I don't know what you're trying to do, but isn't that weird, that you instantiate an object of a parent class in the child class?
If what you're trying to do is access parent's methods through child's you may try:
1 2 3 4 5 6 7 8
class A {
protected:
virtualvoid render() { /*render stuff*/ }
};
class B: public A {
protected:
virtualvoid render() { A::render(); /*render stuff*/ }
};
class A {
protected:
int a;
virtualvoid render() {
/*render Myself*/
}
};
class B: public A {
public:
std::list<A*> displayObjects;
protected:
virtualvoid render() {
/* Render myself */
// and then render my children
<iterator for displayObjects> it;
for(each it++) {
(**it).a = 0;
(**it).render();
}
}
};
I would like to give derived classes of A the ability to access information about instances of A (functions and variables), and at the same time keep the information from classes outside of the heirarchy. Is this possible?
What I assume you're going for is the classic example of a screen renderer when using polymorphism.
(Please note: I use an old Borland compiler [STILL SUPPORTS OWL!!!], so some code might be outdated)
1 2 3 4 5 6 7 8 9 10 11
class Shape{ //This is your class A
virtualvoid Render()=0; //Pure virtual, no definition
};
class Rect: public Shape{
virtualvoid Render() {/*draw a rectangle*/};
};
class Circle: public Shape{
virtualvoid Render() {/*draw a circle*/};
};
etc.
Of course, just A circle or A rectangle isn't probably what you want. You can define members in base class Shape to use as parameters.
Once you do all of the coding, you can create new objects (of type Circle or Rect or whatever), cast the, to a Shape *. and add them to a list or array to be passed to the screen manager (which will iterate through the list and call list[num]->Render();).