Home > Backend Development > C++ > Why Does Calling a Virtual Function in a Base Class Constructor Print the Base Class Value, Not the Derived Class Value?

Why Does Calling a Virtual Function in a Base Class Constructor Print the Base Class Value, Not the Derived Class Value?

Mary-Kate Olsen
Release: 2024-12-21 05:24:10
Original
402 people have browsed it

Why Does Calling a Virtual Function in a Base Class Constructor Print the Base Class Value, Not the Derived Class Value?

Constructor Invocation of Virtual Functions

In C , constructors are responsible for initializing objects. However, when dealing with derived classes and virtual functions, specific behavior can arise that may not be immediately intuitive.

Consider the following example:

#include <iostream>

struct base {
   virtual const int value() const {
      return 0;
   }
   base() {
      std::cout << value() << std::endl;
   }
   virtual ~base() {}
};

struct derived : public base {
   virtual const int value() const {
      return 1;
   }
};

int main(void) {
   derived example;
}
Copy after login

In this example, we have a base class base with a virtual function value(). A derived class derived inherits from base and overrides value(). The constructor in base attempts to call value() within its constructor.

When the constructor of derived is invoked, the constructor of base is called first. At this point, the object is still in the state of the base class, and value() resolves to the base class's implementation. This is why the program prints "0" instead of the expected "1".

To address this issue, we need to ensure that the object is fully initialized as the derived class before calling value() in the constructor. One way to achieve this is to delay the call to value() until after the constructor of derived has been executed, which can be done by using a virtual function in the derived class constructor.

The above is the detailed content of Why Does Calling a Virtual Function in a Base Class Constructor Print the Base Class Value, Not the Derived Class Value?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template