What is a pure virtual (abstract) method, and how does it force subclasses to provide behaviour?
Last updated
A pure virtual (abstract) method is a method declared without an implementation: it defines a contract the class promises but leaves the body for subclasses to supply.
It has a signature but no body: Declared with
= 0in C++,abstractin Java/C#, or@abstractmethodin Python.It makes the class abstract: You cannot instantiate a class with an unimplemented pure virtual method; the compiler/runtime forbids it.
It forces subclasses to provide behaviour: A concrete subclass must override every abstract method or it too remains abstract and cannot be instantiated.
It enables polymorphism: Callers program to the base type and dispatch dynamically to whatever concrete implementation the subclass supplied.
[lang:python]
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return 3.14159 * self.r ** 2
# Shape() -> TypeError: can't instantiate abstract class
- https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
- https://medium.com/@kumardeeepak392/understanding-abstraction-in-c-abstract-classes-pure-virtual-functions-interview-questions-2c4734e38ad4
- https://www.geeksforgeeks.org/java/abstract-methods-in-java-with-examples/
- https://devsunite.com/resources/core-subjects/oop/abstract-classes-and-pure-virtual-functions
- https://bcalabs.org/subject/pure-virtual-function-and-abstract-class
- https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/override