Home > Backend Development > C++ > Why Do C Virtual Functions Called from a Constructor Return the Base Class Value?

Why Do C Virtual Functions Called from a Constructor Return the Base Class Value?

Susan Sarandon
Release: 2024-12-06 13:24:12
Original
695 people have browsed it

Why Do C   Virtual Functions Called from a Constructor Return the Base Class Value?

Why C Virtual Functions Invoked from Constructors May Behave Unexpectedly

In C , virtual functions provide dynamic binding, allowing a derived class to override a function defined in its base class. However, invoking a virtual function from a constructor can lead to unexpected results.

Consider the following code snippet:

#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

The code defines two classes, base and derived, with a virtual function value(). The base constructor calls value() during object initialization. One might expect the code to print "1" when run, as the object of type derived is being constructed. However, it outputs "0" instead.

The reason for this behavior lies in the order of object construction. When initializing an object of type derived, the base class constructor is called first. At this point, the object is not yet fully initialized and may not have its derived-class-specific data members initialized. As a result, calling value() from the base constructor invokes the base class implementation of the function, which returns 0.

To achieve the intended behavior, the value() function should be called from a post-construction stage, where the object is guaranteed to be fully initialized. This can be done by overriding the value() function in the derived class and calling it from a separate method that is guaranteed to be called after construction. For example:

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

In this case, the get_value() method can be called from the constructor to obtain the correct value of "1".

The above is the detailed content of Why Do C Virtual Functions Called from a Constructor Return the Base 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