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

对着背影说爱祢 提交于 2019-11-29 09:10:38
#define abstract
DevSolar

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

Varun_k

No, you can't use abstract as a keyword because there is no such keyword available in C++.

If you want make a class as an in C++ abstract you can declare at least one function as pure virtual function.

But in derived class you must provide definition else its give compilation error .

Example:

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

note:

You can used abstract as a variable name, class name because, as I told you, abstract is not a keyword in C++.

There is no keyword 'abstract' but a pure virtual function turns a class in to abstract class which one can extend and re use as an interface.

Varun_k

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. You need to have at least one pure virtual function in a class to be abstract.

class SomeClass {
public:
   virtual void pure_virtual() = 0;  // a pure virtual function
};
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!