Easy Tutorial
❮ Basic Knowledge Summary Of Spring Docker Clear Command ❯

Differences Between C++ Virtual Functions and Pure Virtual Functions

Category Programming Techniques

First: Emphasize a concept

Defining a function as a virtual function does not mean the function is unimplemented.

Defining it as a virtual function allows the use of a base class pointer to call the derived class's function.

Defining a function as a pure virtual function means the function is not implemented.

Defining a pure virtual function is to implement an interface, serving as a specification, requiring programmers who inherit this class to implement the function.

1. Introduction

Suppose we have the following class hierarchy:

Example

class A
{
public:
    virtual void foo()
    {
        cout << "A::foo() is called" << endl;
    }
};
class B : public A
{
public:
    void foo()
    {
        cout << "B::foo() is called" << endl;
    }
};
int main(void)
{
    A *a = new B();
    a->foo();   // Here, although a is a pointer to A, the function (foo) called is B's!
    return 0;
}

This example is a typical application of virtual functions. It demonstrates the concept of "late binding" or "dynamic binding," where the call to a class function is determined at runtime rather than compile time. Since it's not possible to determine at the time of coding whether the base class's function or the derived class's function will be called, it is referred to as a "virtual" function.

Virtual functions can only achieve polymorphism through pointers or references.


C++ Pure Virtual Functions

1. Definition

A pure virtual function is a virtual function declared in a base class that has no definition relative to the base class. It requires any derived class to define its own implementation method. The way to implement a pure virtual function in a base class is to add =0 after the function prototype:

virtual void function1() = 0;

2. Reasons for Introduction

  1. To facilitate the use of polymorphism, we often need to define virtual functions in the base class.
  2. In many cases, it is unreasonable for the base class itself to generate objects. For example, an Animal base class can derive Tiger, Peacock, etc., but generating an Animal object itself is not logical.

To solve these issues, the concept of a pure virtual function is introduced. By defining a function as a pure virtual function (virtual ReturnType Function() = 0;), the compiler requires that it must be overridden in the derived class to achieve polymorphism. Classes containing pure virtual functions are called abstract classes and cannot generate objects. This effectively addresses the above issues.

A class with a pure virtual function is an abstract class. Therefore, users cannot create instances of the class, only instances of its derived classes.

The most notable feature of pure virtual functions is that they must be re-declared in the inherited class (without the =0, otherwise the derived class cannot be instantiated), and they often have no definition in the abstract class.

The purpose of defining a pure virtual function is to ensure that the derived class inherits only the function's interface.

The significance of a pure virtual function is to allow all class objects (mainly derived class objects) to perform the actions of the pure virtual function, but the class cannot provide a reasonable default implementation. So, the declaration of a pure virtual function tells the designer of the subclass, "You must provide an implementation for this pure virtual function, but I don't know how you will implement it."


Introduction to Abstract Classes

An abstract class is a special kind of class, created for the purpose of abstraction and design, located at the upper level of the inheritance hierarchy.

1. Definition of Abstract Class: A class with a pure virtual function is called an abstract class.

2. Role of Abstract Class: The main role of an abstract class is to organize related operations as an interface in an inheritance hierarchy, providing a common root for derived classes, which implement operations as an interface in their base class. Therefore, the derived class actually describes a set of subclass operation interfaces with common semantics, which are also passed to the subclass. The subclass can implement these semantics, or it can pass these semantics to its own subclass.

3. Notes on Using Abstract Classes:


Summary:

  1. A pure virtual function is declared as follows: virtual void function1() = 0; A pure virtual function must not have a definition; it is used to standardize the behavior of derived classes, i.e., as an interface. A class containing a pure virtual function is an abstract class, which cannot define instances but can declare pointers or references to the concrete class that implements the abstract class.

  2. A virtual function is declared as follows: virtual ReturnType FunctionName(Parameter) A virtual function must be implemented; if not, the compiler will report an error:

    error LNK****: unresolved external symbol "public: virtual void __thiscall ClassName::virtualFunctionName(void)"
    
  3. For virtual functions, both the parent and child classes have their own versions. Dynamic binding occurs when called in a polymorphic manner.

  4. A subclass that implements a pure virtual function turns that function into a virtual function in the subclass. Subclasses of this subclass can override this virtual function, and dynamic binding occurs when called in a polymorphic manner.

  5. Virtual functions in C++ are used to implement polymorphism. The core idea is to access functions defined in derived classes through a base class.

  6. When there is dynamic memory allocation on the heap, the destructor must be a virtual function, but it does not need to be a pure virtual function.

  7. Friend functions are not member functions, and only member functions can be virtual. Therefore, friend functions cannot be virtual functions. However, the virtual issue of friend functions can be resolved by having the friend function call the virtual member function.

  8. The destructor should be a virtual function, which will call the destructor corresponding to the object type. Therefore, if the pointer points to a subclass object, the subclass's destructor will be called, followed by the automatic call to the base class's destructor.

A class with a pure virtual function is an abstract class and cannot generate objects; it can only be derived. If the pure virtual function of its derived class is not overridden, then its derived class is still an abstract class.

Defining a pure virtual function is to prevent the base class from being instantiated, as instantiating such an abstract data structure has no meaning, or providing an implementation has no meaning.

Personally, I believe the introduction of pure virtual functions serves two purposes:

  1. For safety, to avoid any unintentional and unknown results that need to be explicitly defined, prompting subclasses to implement what is necessary.
  2. For efficiency, not program execution efficiency, but coding efficiency.

Original Source: https://blog.csdn.net/hackbuteer1/article/details/7558868

❮ Basic Knowledge Summary Of Spring Docker Clear Command ❯