protected inheritance question

I have two classes:
1
2
3
4
5
6
7
8
9
class A {
protected:
virtual void render() { /*render stuff*/ }
};
class B: public A {
protected:
A *aInstance;
virtual void 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
Last edited on
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:
virtual void render() { /*render stuff*/ }
};
class B: public A {
protected:
virtual void render() { A::render(); /*render stuff*/ }
};
It's not that simple. I am creating a UI with nested objects. so my code really looks more like
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class A {
protected:
  int a;
  virtual void render() { 
    /*render Myself*/ 
  }
};
class B: public A {
public:
  std::list<A*> displayObjects;
protected:
  virtual void 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?
Last edited on
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
   virtual void Render()=0; //Pure virtual, no definition
};

class Rect: public Shape{
   virtual void Render() {/*draw a rectangle*/};
};

class Circle: public Shape{
    virtual void 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();).
Last edited on
Topic archived. No new replies allowed.