Some C++ Class questions...
-
- Posts: 1638
- Joined: Mon Apr 30, 2007 3:24 am
- Location: Montreal, CANADA
- Contact:
-
- Admin
- Posts: 3590
- Joined: Mon Oct 09, 2006 9:36 am
- Location: Scotland - gonnae no slag aff mah Engleesh
- Contact:
Not if we're just talking about passing structs as parameters/return values. Think it through. Memory for parameters/return values comes from where...?christianclavet wrote:Yes, Fireside. But will your application use more memory? I think so.
Please upload candidate patches to the tracker.
Need help now? IRC to #irrlicht on irc.freenode.net
How To Ask Questions The Smart Way
Need help now? IRC to #irrlicht on irc.freenode.net
How To Ask Questions The Smart Way
Here is how it is outlined in Design Patterns by Gamma, Helm, Johnson, and Vlissides (the "Gang of Four"):christianclavet wrote: What is a singleton?
Code: Select all
class GameInfo {
public:
static GameInfo* Instance();
virtual void DoSomething();
//Public members here
protected:
GameInfo();
//Protected members here
private:
static GameInfo* _instance;
//Private members here
};
GameInfo* GameInfo::_instance = 0;
GameInfo* GameInfo::Instance() {
if(_instance == 0)
_instance = new GameInfo;
return _instance;
}
First of all, if you used static data and functions, you can't take advantage of polymorphism. What is the need for polymorphism if you're only ever going to have one instance? Code reuse.
Any code that refers to GameInfo::Instance()->DoSomething() would not have to be changed if you choose to reuse it in another game.
So let's say you are making a game called PuckMan. You could have something like this:
Code: Select all
class PuckManInfo : public GameInfo{
public:
static GameInfo* Instance();
virtual void DoSomething();
//Public members here
protected:
PuckManInfo();
//Protected members here
private:
//Private members here
};
GameInfo* PuckManInfo::Instance() {
if(_instance == 0)
_instance = new PuckManInfo;
return _instance;
}
Code: Select all
class BreakOutInfo : public GameInfo{
public:
static GameInfo* Instance();
virtual void DoSomething();
//Public members here
protected:
BreakOutInfo();
//Protected members here
private:
//Private members here
};
GameInfo* BreakOutInfo::Instance() {
if(_instance == 0)
_instance = new BreakOutInfo;
return _instance;
}
Code: Select all
int main()
{
PuckManInfo::Instance();
// PuckMan main function
Code: Select all
GameInfo::Instance()->DoSomething();
That being said, it might be more expedient to just have something like this:
Code: Select all
class GameInfo {
public:
static void DoSomething();
static int getData();
//public members (all static)
protected:
static int data;
//protected members (all static)
private:
//private members (all static)
};