Abstract Base Class (ABC)

Abstract classes don’t have any instances. They exist only to define common shapes of descendant classes.

  • their purpose is to provide a framework to organize and define subclasses

Concrete classes, on the other hand, are designed to inherit the properties of the common ABCs, and extend them by adding new instance variables and methods peculiar to them.

Example

In the above example, Monster, Humanoid, Weapon, and GameObject are all abstract base class (ABC).

Abstract Class

Classes that declare a pure virtual function are called Abstract Class. Abstract classes cannot be instantiated as objects.

class Square {
	public:
		virtual float getArea() const = 0;
}

Warning

In C++, you cannot create objects directly from abstract base classes (ABCs) because ABCs are incomplete types and cannot be instantiated. An abstract base class is a class that has at least one pure virtual function, making it impossible to create objects of that class.

However, you can create pointer to ABCs. See Polymorphism for an example of this.

Pure Virtual Function

Sometimes, the parent class defines only a shell of a method, expecting the child classes to provide an appropriate definition - These are called Pure Virtual Method

virtual void function() = 0;

Can you instantiate derived classes of abstract classes?

We saw in Object Construction that the parent class gets called first, then the derived class. So if derived class calls the constructor of an abstract parent class, isn’t that illegal behavior, because it is trying to instantiate it?

  • Calling a constructor is NOT the same as instantiation. A constructor simply initializes the member fields and calls the constructor body.
  • What if you want the parent class to call the implementation of the child class? There is a DESIGN PATTERN FOR THIS!! TODO

So a Constructor initializes? and then to know what type to instantiate, it just looks at the last constructor? Or is it when the first constructor gets called? I really need to understand how compilers work.

Concrete Class

A class that overrides all of its parents pure virtual functions is called a concrete class. Concrete classes can be instantiated.

Other Things

I lost a point in the midterm for this, but a concrete class CAN have an abstract subclass. You can always just add another Pure Virtual Method to make a class abstract.

  • However, this is generally indicative of bad design