inheritance situation?

Ok. so i'm in a bit of an unusual situation trying to structure this program and I Just don't know how to do it logically

Ok basically its getting to be able to draw whats defined in a different class.
this is my general situation. (minimum code to understand the situation, not real testable code)

1
2
3
4
5
6
7
8
class Game{
private:
 window gamewindow;
stuffneeded thisstuff;
public:
void dowhatineed(){
gamewindow.draw(thisstuff);
}

see i could do this. and it work fine. but i need to take "thisstuff" and put it in a different class for organisation.

so i would try this
1
2
3
4
5
6
class stuff{
public:
// dont have access to window to make a draw.
private:
stuffneeded thisstuff;
};


1
2
3
4
5
6
7
class Game : public stuff{
private:
 window gamewindow;
public:
void dowhatineed(){
//gamewindow.draw(thisstuff); <-- cant
}

well now i don't have access to gamewindow to draw "thisstuff".
wouldnt it be bad to inherit privately? isn't that the same as basically global variables?
A Game is not a stuff, so Game should not inherit from it.

This is a case for a double dispatch pattern:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// A little ugly on one file
// I'm just making everything public so I type less
// Also I'm using manual memory management
// simply to keep it short and sweet

#include <iostream>

struct Window;

struct Renderable
{
  virtual void render( Window& ) = 0;
};

struct Window
{
  void render( Renderable& renderable )
  {
    // give the objects this window for operations
    renderable.render( *this );
  }

  void print( const char* str )
  {
    std::cout << str << '\n';
  }
};

struct Square : public Renderable
{
  void render( Window& window )
  {
    // use the window
    window.print( "A square" );
  }
};

struct Circle : public Renderable
{
  void render( Window& window )
  {
    window.print( "A circle" );
  }
};

struct Game
{
  Window window;
  Renderable *renderables[2];

  void update( void )
  {
    for ( int i = 0; i < 2; ++i )
    {
      // tell the window to render the objects
      window.render( *renderables[i] );
    }
  }
};

int main( void )
{
  Game the_game;
  the_game.renderables[0] = new Square();
  the_game.renderables[1] = new Circle();

  the_game.update();

  for ( int i = 0; i < 2 ; ++i )
    delete the_game.renderables[i];

  return 0;
}
Last edited on
Topic archived. No new replies allowed.