Home > Backend Development > C++ > How to Correctly Initialize Base Class Member Variables in a Derived Class Constructor?

How to Correctly Initialize Base Class Member Variables in a Derived Class Constructor?

Linda Hamilton
Release: 2024-12-05 01:14:10
Original
720 people have browsed it

How to Correctly Initialize Base Class Member Variables in a Derived Class Constructor?

How to Initialize Base Class Member Variables in Derived Class Constructor

In object-oriented programming, it's common to have derived classes that inherit from base classes. When creating a constructor in a derived class, it's essential to properly initialize member variables inherited from the base class.

Consider the following code:

class A {
public:
    int a, b;
};

class B : public A {
    B() : A(), a(0), b(0) {
    }
};
Copy after login

In this example, the derived class B attempts to initialize the member variables a and b within its own constructor. However, this is an incorrect approach. The correct way to initialize base class member variables in a derived class is to use the base class's constructor:

class A {
protected:
    A(int a, int b) : a(a), b(b) {} // Accessible to derived classes
private:
    int a, b; // Keep these variables private in A
};

class B : public A {
public:
    B() : A(0, 0) // Calls A's constructor, initializing a and b in A to 0.
    {
    }
};
Copy after login

By making the base class constructor accessible (protected or public) and calling it in the derived class's constructor, we properly initialize the inherited member variables. This approach ensures that the base class is properly initialized before the derived class code executes.

Note that making the base class member variables public in the derived class (as in the incorrect example) is not recommended as it breaks the encapsulation principle, allowing external access to protected or private data.

The above is the detailed content of How to Correctly Initialize Base Class Member Variables in a Derived Class Constructor?. 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