How to Utilize Base Class's Constructors and Assignment Operator in C
A common scenario arises when inheriting from a base class and intending to override specific functions while maintaining the base class's set of constructors and assignment operators. In this instance, rewritten these constructs may be unnecessary, as C offers viable alternatives.
Explicit Invocation of Constructors and Assignment Operators:
In this approach, the derived class explicitly calls the base class's constructors and assignment operator within its own constructors and assignment operator definitions. For example, consider the following:
<code class="cpp">class Base { public: Base(const Base& b) { /*...*/ } Base& operator=(const Base& b) { /*...*/ } }; class Derived : public Base { public: Derived(const Derived& d) : Base(d), // Base constructor additional_(d.additional_) // Additional member initialization { } Derived& operator=(const Derived& d) { Base::operator=(d); // Base assignment operator additional_ = d.additional_; return *this; } };</code>
Implicit Function Dispatch:
In cases where the derived class does not explicitly override the base class's assignment operator or copy constructor, the compiler automatically dispatches to the appropriate base class methods. This functionality is demonstrated below:
<code class="cpp">class Base { int value_; }; class Derived : public Base { public: Derived& operator=(const Derived& d) { Base::operator=(d); // Implicit invocation of base operator= // Perform derived-specific assignment return *this; } }; </code>
The above is the detailed content of How to Use Base Class Constructors and Assignment Operators in Derived Classes?. For more information, please follow other related articles on the PHP Chinese website!