Why do we need abstract classes in C++?

前端 未结 10 2107
暗喜
暗喜 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:45

    The purpose of an abstract class is to define a common protocol for a set of concrete subclasses. This is useful when defining objects that share code, abstract ideas, etc.

    Abstract classes have no instances. An abstract class must have at least one deferred method (or function). To accomplish this in C++, a pure virtual member function is declared but not defined in the abstract class:

    class MyClass {
        virtual void pureVirtualFunction() = 0;
    }
    

    Attempts to instantiate an abstract class will always result in a compiler error.

    "What does defining an abstract base class provide that isn't provided by creating each necessary function in each actual class?"

    The main idea here is code reuse and proper partitioning across classes. It makes more sense to define a function once in a parent class rather than defining over and over again in multiple subclasses:

    class A {
       void func1();
       virtual void func2() = 0;
    }
    
    class B : public A {
       // inherits A's func1()
       virtual void func2();   // Function defined in implementation file
    }
    
    class C : public A {
       // inherits A's func1()
       virtual void func2();   // Function defined in implementation file
    }
    

提交回复
热议问题