Home > Article > Backend Development > How do I leverage Base Class\'s constructors and assignment operator in C ?
How to Leverage Base Class's Constructors and Assignment Operator in C
In C , inheriting classes can inherit the behavior of the base class, including constructors and assignment operators. Consider a base class B with a set of constructors and an assignment operator:
<code class="cpp">class B { public: B(); B(const string& s); B(const B& b) { *this = b; } B& operator=(const B& b); };</code>
Now, you want to create a derived class D that overrides the foo() function while inheriting the same set of constructors, including the copy constructor and assignment operator. However, to avoid duplication, you want to use the existing constructors and operators in B.
Explicit Invocation:
You can explicitly call the base class's constructors and assignment operator within the derived class's constructor and assignment operator, respectively. This ensures that the base class's member variables are properly initialized.
<code class="cpp">class D : public B { public: D(const D& d) : B(d), additional_(d.additional_) {} D& operator=(const D& d) { B::operator=(d); additional_ = d.additional_; return *this; } private: int additional_; };</code>
Implicit Invocation:
Interestingly, even if you don't explicitly define the copy constructor and assignment operator in the derived class, the compiler will generate default versions. These default versions implicitly call the base class's copy constructor and assignment operator, respectively.
For example, with the following base class:
<code class="cpp">class ImplicitBase { int value_; };</code>
The following derived class's assignment operator implicitly calls the base class's assignment operator:
<code class="cpp">class Derived : public ImplicitBase { const char* name_; public: Derived& operator=(const Derived& d) { ImplicitBase::operator=(d); // Implicit call to base class's assignment operator name_ = strdup(d.name_); return *this; } };</code>
The above is the detailed content of How do I leverage Base Class\'s constructors and assignment operator in C ?. For more information, please follow other related articles on the PHP Chinese website!