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

前端 未结 10 2225
梦如初夏
梦如初夏 2020-12-06 09:10

Can we write abstract keyword in C++ class?

相关标签:
10条回答
  • 2020-12-06 09:50

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

    0 讨论(0)
  • 2020-12-06 09:50

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

    Here is a good reference cplusplus.com

    0 讨论(0)
  • 2020-12-06 09:51

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

    0 讨论(0)
  • 2020-12-06 09:54

    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

    0 讨论(0)
  • 2020-12-06 10:04

    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()
        {
        }
    };
    
    0 讨论(0)
  • 2020-12-06 10:06

    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.

    0 讨论(0)
提交回复
热议问题