Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract class without abstract methods

Tags:

c++

Is it possible to make a class abstract in C++ without declaring any abstract methods? Currently, I have a Sprite class with a StaticSprite and DynamicSprite subclass. I would like to make the Sprite class abstract.

The problem is that there aren't any methods they share. Well, both StaticSprite and DynamicSprite might share a draw()-method, but the parameters of this method are different so this isn't an option.

Thank you!

EDIT: Here is the code to demonstrate what I'm trying to do:

Sprite:

class Sprite
{
    public:
        Sprite(HINSTANCE hAppInst, int imageID, int maskID);
        ~Sprite();

    protected:
        HINSTANCE hAppInst;
        HBITMAP hImage;
        HBITMAP hMask;
        BITMAP imageBM;
        BITMAP maskBM;
        HDC hSpriteDC;
};

Staticsprite:

class StaticSprite : public Sprite
{
    public:
        StaticSprite(HINSTANCE hAppInst, int imageID, int maskID);
        ~StaticSprite();

        void draw(Position* pos, HDC hBackbufferDC);
};

Dynamicsprite:

class DynamicSprite : public Sprite
{
    public:
        DynamicSprite(HINSTANCE hAppInst, int imageID, int maskID);
        ~DynamicSprite();

        void draw(HDC hBackbufferDC);
};

As you see, it's useless to create a Sprite-object, so I would like to make that class abstract. But I can't make draw() abstract as it uses different parameters.

like image 399
Bv202 Avatar asked Mar 07 '11 21:03

Bv202


People also ask

Can there be abstract class without abstract methods in it?

An abstract class is a class that is declared abstract —it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class.

Why we need abstract class without abstract method?

The abstract class used in java signifies that you can't create an object of the class. And an abstract method the subclasses have to provide an implementation for that method. So you can easily define an abstract class without any abstract method.

What happens if I will not provide an abstract method in abstract class and interface?

If you don't a compile time error will be generated for each unimplemented method saying “InterfaceExample is not abstract and does not override abstract method method_name in interface_name”.


1 Answers

You can declare your destructor as pure virtual, since all classes have one.

class AbstractClass
{
public:
    virtual ~AbstractClass() = 0 ;
} ;

However, you will need to define this destructor elsewhere.

AbstractClass::~AbstractClass() {}
like image 89
Tugrul Ates Avatar answered Oct 19 '22 09:10

Tugrul Ates