sharing class pointers for engine layout

Started by
1 comment, last by Krohm 11 years, 9 months ago
hey there,

so i was wondering how you would make classes that could use pointers form other classes. i need this in irrlicht so it will play niecly with every other abstracted piece of the game enigne.

here is an example of what i need:


class class1
{
device *myPointer;
void initializeGame();
}
class class2
{
void load model(); //functions require the same pointer from the first class
}


any input is awesome,
thanks
Advertisement
I am not sure if your question is really this "basic", but otherwise I will be happy to re-reply smile.png

Passing pointers around via either constructors (or get/set) or directly as function parameters are the most common ways.


// Passing pointer via constructor.
class ClassA
{
public:
ClassA(Device *device) : mDevice(device) {}
Device *GetDevice() const { return mDevice; }
void SetDevice(Device *device) { mDevice = device; }
void LoadModel(); // uses mDevice internally.
private:
Device *mDevice;
};
// Passing pointer directly.
class ClassB
{
public:
void LoadModel(Device *device);
};


If your class1 needs to use ClassA's LoadModel, it would either call constructor ClassA::ClassA(class1::myPointer) or ClassA::Get/SetDevice and then use ClassA::LoadModel();
If your class2 needs to use ClassB's LoadModel, it would just call ClassB::LoadModel(class1::myPointer).
(note that all the :: is just to write the operations as members - normally you would use . or -> instead of :: ).

ClassA saves the pointer in constructor (can be altered using Get/SetDevice, but these are not necessary) for use by its methods, while ClassB's methods require the pointer to be directly passed when calling them.
The latter is more flexible, since the more you couple things together, the more inflexible they get. The former advises you to consider whether or not you want (and need) ClassA to represent a Device pointer within its own state. If most of your (non-static) methods inside a class needs a specific pointer, the former solution can help reduce the amount of parameters.
Consider abstract base classes. They get you the coupling you need, while keeping some separation. This is very good and tends to give better documentation when run through Doxygen as well.

Previously "Krohm"

This topic is closed to new replies.

Advertisement