Overriding Methods within Inherited Classes Problem

I am trying to setup an inheritance system where objects keep track of their *parent's* position. To help visualize what I'm trying to do, think of a window that contains a rectangle on it. Inside the rectangle is a circle. The window has a coordinate position (relative to the computer screen). The rectangle and circle also have a coordinate position, but relative to the window, even though the circle might be drawn inside the rectangle, thus having coordinates both relative to the rectangle and the window.

The code below demonstrates how I am storing and retrieving the coordinate position relative to a parent object.

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
#include <iostream>

class entity {
private:
 int _pos;
 entity* _parent;

protected:
 inline entity* parent() const { return _parent; }
	
public:
 entity() : _pos(0), _parent(NULL) {};
 void childTo(entity* parent) { if (parent != this) _parent = parent; } 
 int position() const {
  int tmp = _pos;
  if (parent() != NULL) tmp += parent()->position();
  return tmp;
 }
 void setPosition(int newP) { _pos = newP; }
};

class object : public entity {
public:
 object() : entity() {};
};

class window : public object {
public:
 window() : object() {};
 //Override so that objects on the window 
 //always return relative to the window and
 //NOT the computer screen
 int position() const { return 0; }
};

class image : public object {
public:
 image() : object() {};
};

int main() {

 window wnd;
 //Allow the window to have a position 
 //set for drawing (relative to the computer screen)
 wnd.setPosition(3);

 image frame;
 frame.childTo(&wnd);
 frame.setPosition(4);

 image pic;
 pic.childTo(&frame);
 pic.setPosition(6);

 std::cout << "Frame position relative to the window (should be 4): " << frame.position() << std::endl;
 std::cout << "Pic position relative to the window (should be 10): " << pic.position() << std::endl;

 std::cin.get();
 return 0;
}


My problem is, why does the int position() const { return 0; } method within the window class not override the base entity class' position() method. And how do I get it to do so?
Make it a virtual function in the parent.
Wow, so simple. Thank you for your help. I can't believe I missed that.
Topic archived. No new replies allowed.