Proper use of inheritance

This is the kind of functionality I want: to be able to access data of derived Subsystem classes from any class that has a reference to the Context (ideally 1 pointer for each type of derived class).

It appears I'll have to do some pointer casting. Am I doing it wrong?

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

struct Subsystem{
	int mInt;
};

struct Gui: Subsystem{
	int mArray[3];
};

struct Overlay: Subsystem{
	int mData;
};

struct Context{
	Subsystem* mSys[2];
};

int main(){
	using namespace std;

	Context lctx;

	lctx.mSys[0] = new Overlay();
	lctx.mSys[1] = new Gui();
	
	cout << ((Overlay*)lctx.mSys[0])->mData << endl;
	cout << ((Gui*)lctx.mSys[1])->mArray[2] << endl;

	return 0;
}
Last edited on
It seems to work all right so far.

But I don't know if delete mSys[0] is going to free the proper memory of the derived class? Or the base class only?
So poking around I find that the deallocation will be fine, but if I want to ensure the destructor for the derived class is called, I need the base class to have its destructor declared as virtual.

Correct?
If you want to delete a derived object via a base class pointer, you have to make the destructor virtual.
Otherwise you'll get undefined behavior.
Your pointer casting is due to the fact that you are upcasting, meaning you want a pointer of a more specialized class out of a pointer of a more basic class. In these cases, you should use dynamic_cast<> instead of C-style casting, provided you are compiling with RTTI enabled.

And yes, make all your destructors virtual.
you are upcasting, meaning you want a pointer of a more specialized class out of a pointer of a more basic class


That's actually downcasting, not upcasting.

</anal>
Really? My bad. :-P
Thanks, all
Topic archived. No new replies allowed.