Another way to get an abstract class?

Oct 17, 2010 at 11:49am
Heya,

I've got another dreaded problem once again:

I have a class that is so generic that it should only be used for derivations. An abstract class makes sense in this context.. so you'd think, here's the downfall:
It makes no sense to put in pure virtual functions, since, in fact, not every function has to be overridden for the derived class to become valid. The base class musn't be instantiable, while the derived class (with nothing redefined) is valid for usage. How do I achieve this?

Here is the class definition:
1
2
3
4
5
6
7
8
9
class CObject
{   public:
    virtual void OnStep() {};
    virtual void OnEndStep() {};
    virtual void OnDraw() {};
    protected:
    sf::Sprite Sprite;
    private:
    virtual ~CObject();};
Last edited on Oct 17, 2010 at 11:49am
Oct 17, 2010 at 12:07pm
Hello Kyon,

you can use protected constructor/destructor only (not private)

Oct 17, 2010 at 12:20pm
You can make the destructor pure virtual (and public) - but still (have to) provide a body for the destructor.

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
32
33
34
35
36
37
38
 class CObject
{   public:
    virtual void OnStep() {};
    virtual void OnEndStep() {};
    virtual void OnDraw() {};
    protected:
    sf::Sprite Sprite;
    
     public:
    virtual ~CObject()=0;

};

CObject::~CObject () 
{

}

class derived : public CObject
{
public:
    ~derived() 
    {

    };
};
 
 
 int main() 
{  


  CObject co; //This line will give an error because CObject is abstract
  
    derived d;
  
    return 0;  
}
Oct 17, 2010 at 2:46pm
+1 coder777

Don't make the user pay for what they don't use/need (virtual functions add a vtable).

Topic archived. No new replies allowed.