Why do we need abstract classes in C++?

前端 未结 10 2117
暗喜
暗喜 2020-12-14 03:19

I\'ve just learned about polymorphism in my OOP Class and I\'m having a hard time understanding how abstract base classes are useful.

What is the purpose of an abstr

10条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 03:47

    The purpose of an abstract class is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error. (because vtable entry is not filled with memory location for virtual function we mentioned in Abstract Class)

    Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions, which means that it supports the interface declared by the ABC. Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class, is a compilation error.

    Example:

    class mobileinternet
    {
    public:
    virtual enableinternet()=0;//defines as virtual so that each class can overwrite
    };
    
    
    class 2gplan : public mobileinternet
    
    {
        private:
    
             int providelowspeedinternet(); //logic to give less speed.
    
        public:
    
             void enableinternet(int) {
                                         // implement logic
                                     }
    
    };
    
    //similarly
    
    class 3gplan : public enableinternet
    {
       private: high speed logic (different then both of the above)
    
       public: 
              /*    */
    }
    

    here in this example, you can understand.

提交回复
热议问题