C++

Pure virtual function with implementation

25 September 2026 · 9 min read

Pure virtual function with implementation

In the realm of object-oriented programming, especially within languages like C++, the concept of a pure virtual function stands as a cornerstone for achieving abstraction and polymorphism. A pure virtual function is a virtual function declared in a base class that has no definition within that class. Instead, derived classes are expected to provide their own specific implementations. This mechanism allows you to define an interface without committing to a particular implementation in the base class. This provides a flexible blueprint for derived classes, enabling them to implement the functionality in a way that suits their specific needs. This powerful feature is vital for designing robust and extensible software architectures, allowing developers to define abstract behaviors that are then concretized in specialized subclasses. We’ll explore how to navigate this topic with clarity.

Understanding Pure Virtual Functions

A pure virtual function is declared using the “= 0” syntax in C++. For example, virtual void draw() = 0; declares a pure virtual function named “draw.” When a class contains at least one pure virtual function, it becomes an abstract class. Abstract classes cannot be instantiated directly. Instead, they serve as blueprints for other classes. Any class that inherits from an abstract class must provide an implementation for all of the pure virtual functions it inherits, unless it, too, is declared as an abstract class. This ensures that concrete (non-abstract) classes provide a complete implementation of the interface defined by the abstract class.

This mechanism is powerful because it enforces a contract between the base class and its derived classes. The base class defines what functionality must be provided, while the derived classes determine how that functionality is implemented. This promotes code reusability and maintainability, as changes to the base class interface are automatically reflected in all derived classes. Furthermore, this supports polymorphism, allowing objects of different classes to be treated as objects of a common type, as long as they inherit from the same abstract class. This is crucial for designing flexible and extensible software systems.

Consider a scenario where you are designing a graphics library. You might define an abstract class called “Shape” with a pure virtual function called “draw.” Different shapes, such as circles, squares, and triangles, can then inherit from the “Shape” class and provide their own specific implementations of the “draw” function. This allows you to treat all shapes uniformly, regardless of their specific type, and draw them all using the same interface. According to a study by Gamma et al. in “Design Patterns: Elements of Reusable Object-Oriented Software,” this type of abstraction is essential for building flexible and maintainable software systems. Explore more on design patterns here.

Implementing Pure Virtual Functions

While a pure virtual function is typically declared without a definition in the base class, it is possible to provide an implementation. This might seem counterintuitive, but it can be useful in certain situations. For example, the base class implementation can provide a default behavior that can be overridden by derived classes if needed. To provide an implementation for a pure virtual function, you simply define the function in the base class as you would any other member function. However, even if a pure virtual function has an implementation, the class remains abstract, and derived classes are still required to provide their own implementations.

The main reason to provide an implementation for a pure virtual function is to offer common functionality that derived classes can reuse. The derived class can then call the base class implementation using the scope resolution operator (::) and extend or modify the behavior as needed. This can help to reduce code duplication and improve code maintainability. This is a common technique used in frameworks and libraries to provide a base level of functionality that can be customized by users.

For instance, imagine an abstract class “Logger” with a pure virtual function “logMessage.” The base class implementation might handle formatting the message and writing it to a common log file. Derived classes can then override the “logMessage” function to add additional information to the log message or write it to a different destination. This approach allows for a flexible and extensible logging system. The featured snippet-optimized paragraph is as follows: One key advantage of providing a base implementation is that it allows for a consistent baseline behavior across all derived classes, while still allowing them to customize the functionality as needed. This promotes code reuse and reduces the risk of errors caused by inconsistent implementations.

Benefits of Using Pure Virtual Functions

The use of pure virtual functions offers several significant benefits in object-oriented design:

  • Abstraction: They enforce a clear separation between interface and implementation, allowing you to define abstract behaviors without committing to a specific implementation.
  • Polymorphism: They enable objects of different classes to be treated as objects of a common type, promoting code reusability and flexibility.
  • Code Maintainability: Changes to the base class interface are automatically reflected in all derived classes, reducing the risk of inconsistencies and errors.

By using pure virtual functions, you can design more robust, flexible, and maintainable software systems. They allow you to define clear contracts between classes, promote code reuse, and support polymorphism. These are essential principles of object-oriented design that can help you to build better software.

Furthermore, using pure virtual functions aligns with the principles of the Dependency Inversion Principle (DIP), one of the SOLID principles of object-oriented design. According to Robert C. Martin in “Clean Architecture: A Craftsman’s Guide to Software Structure and Design,” DIP states that high-level modules should not depend on low-level modules. Both should depend on abstractions. Pure virtual functions facilitate this by defining abstractions (interfaces) that both high-level and low-level modules can depend on, reducing coupling and increasing modularity. [External Link 1: Dependency Inversion Principle]

Practical Examples and Use Cases

Consider the design of a device driver system. You might have an abstract class called “Device” with pure virtual functions such as “readData” and “writeData.” Different device drivers, such as for a keyboard, mouse, or network card, can then inherit from the “Device” class and provide their own specific implementations of these functions. This allows the operating system to interact with different devices uniformly, regardless of their specific type.

Another common use case is in the design of graphical user interfaces (GUIs). You might have an abstract class called “Widget” with a pure virtual function called “draw.” Different widgets, such as buttons, text boxes, and scroll bars, can then inherit from the “Widget” class and provide their own specific implementations of the “draw” function. This allows the GUI system to draw different widgets uniformly, regardless of their specific type.

Let’s look at a more concrete example using C++ code:

  1. Define the abstract class with the pure virtual function: ``` class Animal { public: virtual void makeSound() = 0; // Pure virtual function };
  2. Create derived classes that implement the pure virtual function: ``` class Dog : public Animal { public: void makeSound() override { std::cout « “Woof!” « std::endl; } }; class Cat : public Animal { public: void makeSound() override { std::cout « “Meow!” « std::endl; } };
  3. Use the derived classes: ``` int main() { Dog myDog; Cat myCat; myDog.makeSound(); // Output: Woof! myCat.makeSound(); // Output: Meow! return 0; }
Infographic here
FAQ ---
What happens if a derived class does not implement a **pure virtual function**?
If a derived class does not implement all of the **pure virtual functions** inherited from its base class, the derived class becomes an abstract class itself and cannot be instantiated.
Can a **pure virtual function** have an implementation?
Yes, a **pure virtual function** can have an implementation in the base class. However, the class remains abstract, and derived classes are still required to provide their own implementations (which can call the base class implementation if desired).
Why use **pure virtual functions** instead of regular virtual functions?
**Pure virtual functions** enforce a contract between the base class and its derived classes, ensuring that derived classes provide a specific implementation for a given function. Regular virtual functions, on the other hand, provide a default implementation that derived classes can optionally override. The choice depends on whether the base class implementation is optional or mandatory.
By leveraging **pure virtual functions**, you gain a powerful tool for designing flexible and extensible object-oriented systems. Understanding their purpose and proper implementation is crucial for creating well-structured and maintainable code. For further reading, explore resources from the C++ documentation \[[External Link 2: cppreference.com](https://en.cppreference.com/w/cpp/language/abstract_class)\] and related design pattern guides. Understanding these nuances sets you apart as a proficient software developer. \[External Link 3: [GeeksforGeeks](https://www.geeksforgeeks.org/pure-virtual-functions-and-abstract-classes/)\]

Mastering pure virtual functions elevates your object-oriented programming skills, enabling you to design more robust and adaptable systems. We’ve covered the core principles, implementation details, benefits, and practical applications of this powerful concept. Now, put this knowledge into practice! Experiment with designing your own abstract classes and derived classes, and explore how pure virtual functions can help you to build better software. Consider diving deeper into related topics like abstract factories or the template method pattern to further enhance your design capabilities. Your journey to becoming a proficient software architect starts with understanding fundamental concepts like this one.

Question & Answer :
My basic understanding is that there is no implementation for a pure virtual function, however, I was told there might be implementation for pure virtual function.

class A { public: virtual void f() = 0; }; void A::f() { cout<<"Test"<<endl; } 

Is code above OK?

What’s the purpose to make it a pure virtual function with an implementation?

A pure virtual function must be implemented in a derived type that will be directly instantiated, however the base type can still define an implementation. A derived class can explicitly call the base class implementation (if access permissions allow it) by using a fully-scoped name (by calling A::f() in your example - if A::f() were public or protected). Something like:

class B : public A { virtual void f() { // class B doesn't have anything special to do for f() // so we'll call A's // note that A's declaration of f() would have to be public // or protected to avoid a compile time problem A::f(); } }; 

The use case I can think of off the top of my head is when there’s a more-or-less reasonable default behavior, but the class designer wants that sort-of-default behavior be invoked only explicitly. It can also be the case what you want derived classes to always perform their own work but also be able to call a common set of functionality.

Note that even though it’s permitted by the language, it’s not something that I see commonly used (and the fact that it can be done seems to surprise most C++ programmers, even experienced ones).