Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use `abstract` keyword in C++ class

Tags:

c++

keyword

People also ask

Can the abstract keyword be used with classes?

An abstract keyword can only be used with class and method. An abstract class can contain constructors and static methods. If a class extends the abstract class, it must also implement at least one of the abstract method. An abstract class can contain the main method and the final method.

Is abstract a keyword in C?

Note that we do not have an abstract keyword, but we do have an override keyword, which is super useful so when a function signature changes, you cannot compile until all the classes that derive from your base class have their virtual functions updated accordingly.

What is the use of abstract class in C?

An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function. You declare a pure virtual function by using a pure specifier ( = 0 ) in the declaration of a virtual member function in the class declaration.

Can we use abstract keyword in C++?

The abstract keyword declares either: A type can be used as a base type, but the type itself cannot be instantiated. A type member function can be defined only in a derived type.


#define abstract

No.

Pure virtual functions, in C++, are declared as:

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

Any class having at least one of them is considered abstract.


No, C++ has no keyword abstract. However, you can write pure virtual functions; that's the C++ way of expressing abstract classes.


It is a keyword introduced as part of the C++/CLI language spefication for the .NET framework.


no, you need to have at least one pure virtual function in a class to be abstract.

Here is a good reference cplusplus.com


As others point out, if you add a pure virtual function, the class becomes abstract.

However, if you want to implement an abstract base class with no pure virtual members, I find it useful to make the constructor protected. This way, you force the user to subclass the ABC to use it.

Example:

class Base
{
protected:
    Base()
    {
    }

public:
    void foo()
    {
    }

    void bar()
    {
    }
};

class Child : public Base
{
public:
    Child()
    {
    }
};

actually keyword abstract exists in C++ (VS2010 at least) and I found it can be used to declare a class/struct as non-instantiated.

struct X abstract {
    static int a;
    static void foX(){};
};
int X::a = 0;
struct Y abstract : X { // something static
};
struct Z : X { // regular class
};
int main() {
    X::foX();
    Z Zobj;
    X Xobj;    // error C3622
}

MSDN: https://msdn.microsoft.com/en-us/library/b0z6b513%28v=vs.110%29.aspx