Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare abstract class in c++

Tags:

c++

abstract

How do i declare abstract class?

For example, I know it's using the keyword virtual like:

class test{
public:
virtual void test()=0;
}

My question is can I abstract test class like this? If not why and how

virtual class test{
}
like image 878
Faceless Avatar asked Dec 01 '22 11:12

Faceless


1 Answers

In most cases, your abstract class contains abstract ("pure virtual" in C++ terms) methods:

class Foo {
public:
    virtual ~Foo() = default;
    virtual void bar() = 0;
};

That is sufficient to make it an abstract class:

Foo foo; // gcc says: cannot declare variable 'foo' to be of abstract type 'Foo'

Note that you really want to declare the destructor as virtual in your base class, or you risk undefined behavior when destroying your derived object through a base class pointer.

There also might be cases when you have no abstract methods, but still want to mark your class as abstract. There are two ways:

a. Declare your base destructor as pure virtual:

class Foo {
public:
    virtual ~Foo() = 0;
    virtual void bar() { }
};

Foo::~Foo() = default; // need to define or linker error occurs

b. Declare all your base constructors as protected:

class Foo {
public:
    virtual ~Foo() = default;
    virtual void bar() { }

protected:
    Foo() = default;
};
like image 109
0xF Avatar answered Jan 01 '23 19:01

0xF