• Advertisement

# Statics + Inheritance

This topic is 4254 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

## Recommended Posts

Hi, I'm a bit confused about statics & inheritance. I'm trying to make a singleton base class. I ended up making a templated class to avoid the problems I was having with deriving from a normal base singleton class... but I'd still like to figure this out. If you have a singleton class with these two static members:
class MySingClass
{
public:
static MySingClass * GetInstance();
protected:
...
...
static MySingClass * p_instance;
};


When you derive from this class, does calling GetInstance() from the derived class give you an instance of the derived class? It seems to return type MySingClass* (which makes sense). But how would I make it return type MyDerivedSingClass*? What I'd really like to know is: are there special rules for static functions and static members, with respect to inheritance? Thanks.

#### Share this post

##### Share on other sites
Advertisement
Your derived class would need to implement the GetInstance() function,
static DerivedClass *GetInstance() { if(!p_instance) p_instance = new DerivedClass; return static_cast<DerivedClass*>(p_instance); }

Then users have to do DerivedClass::GetInstance().

#### Share this post

##### Share on other sites
Ok. I didn't want users to have to write a GetInstance() function, so I avoided that. But it seems silly to avoid since it's only a couple lines.

A couple of questions:

1) If you make two derived classes, and call GetInstance() from both of them, won't you end up with a pointer to the same base class static instance?

2) The other thing, that seems wrong in your solution now that I think about it (and invalidates my question #1): don't you need a function to be declared 'virtual' to overwrite it in a derived class? And I know you can't make a function both 'virtual' and 'static'. Hence, I was stuck.

#### Share this post

##### Share on other sites

• Advertisement
• Advertisement
• ### Popular Tags

• Advertisement
• ### Popular Now

• 10
• 11
• 11
• 11
• 9
• Advertisement