cannot instantiate abstract class

I have the following error which I can not resolve.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
f:\projects\080915 state stack v3\source code\singleton.h(26) : error C2259: 'State' : cannot instantiate abstract class
        due to following members:
        'void State::aFunction(void)' : is abstract
        f:\projects\080915 state stack v3\source code\states.h(21) : see declaration of 'State::aFunction'
        f:\projects\080915 state stack v3\source code\singleton.h(25) : while compiling class template member function 'State &Singleton<T>::Instance(void)'
        with
        [
            T=State
        ]
        f:\projects\080915 state stack v3\source code\states.h(18) : see reference to class template instantiation 'Singleton<T>' being compiled
        with
        [
            T=State
        ]


Singleton.h
1
2
3
4
5
6
7
8
9
template<typename T> class Singleton
{
  public:
    static T& Instance()
    {
        static T theSingleInstance;		///- Assumes T has a protected default constructor.
        return theSingleInstance;		///- Returns the only instance.
    } 
};


States.h
1
2
3
4
5
6
7
8
class State : public Singleton<State>
{
protected:
	State(){};
public:
	virtual void aFunction()=0;

};



The reason I am trying to make State a singleton, is because I am deriving several state classes from it and wish for each of those to be singletons.
"Any class with one or more pure virtual functions is an abstract class, and it is illegal to instantiate an object of it. Trying to do so will cause a compile-time error. Putting a virtual function in your class signals two things to clients of your class:
*Don't make an object of this class, derive from it.
*Make sure you override the pure virtual function."
Last edited on
Heh, I managed to work it out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class State
{
protected:
	State(){};
public:
	virtual void aFunction()=0;

};

class stateDerived : public State,  public Singleton<stateDerived>
{
public:
	void aFunction();
	
};


Also, it doesn't seem to matter the order in which you inherit when using multiple inheritance.
In general that statement is wrong, but in your case I agree that it does not matter. Order of inheritance determines the layout of the object in memory and the order in which constructors for the base classes are called which in turn determines the order in which base class members are constructed.
Actually what do you want to achieve here?

Singleton and returning a reference to the instance, and that too through inheritance, very tricky and error-prone, I guess.
Better to review the class design.

Check it out. Good luck :)
Topic archived. No new replies allowed.