简体   繁体   中英

Is an Abstract Class the same thing as a Base Class?

Is an Abstract Class the same thing as a Base Class?

I occasionally see the term Base Class, but when I look up what it means, I tend to see "Abstract Class" thrown around.

Are they just two words that mean basically the same thing?

This is a typical base class Polygon:

class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area ()
      { return 0; }
};

class Rectangle: public Polygon {
  public:
    int area ()
      { return width * height; }
};

class Triangle: public Polygon {
  public:
    int area ()
      { return (width * height / 2); }
};

Abstract base classes are something very similar to the Polygon class in the previous example. They are classes that can only be used as base classes (you cannot instantiate them), and thus are allowed to have virtual member functions without definition (known as pure virtual functions). The syntax is to replace their definition by =0 (and equal sign and a zero):

An abstract base Polygon class could look like this:

// abstract class CPolygon
class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area () =0;
};

One practical difference is that you cannot create objects of an Abstract Base Class whereas you can create objects of Non-abstract Base Class. This difference is almost enough for me to decide when to use which. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM