Saturday, 23 April 2016

inheritance - How to use base class's constructors and assignment operator in C++?



I have a class B with a set of constructors and an assignment operator.



Here it is:



class B

{
public:
B();
B(const string& s);
B(const B& b) { (*this) = b; }
B& operator=(const B & b);

private:
virtual void foo();
// and other private member variables and functions

};


I want to create an inheriting class D that will just override the function foo(), and no other change is required.



But, I want D to have the same set of constructors, including copy constructor and assignment operator as B:



D(const D& d) { (*this) = d; }
D& operator=(const D& d);



Do I have to rewrite all of them in D, or is there a way to use B's constructors and operator? I would especially want to avoid rewriting the assignment operator because it has to access all of B's private member variables.


Answer



You can explicitly call constructors and assignment operators:



class Base {
//...
public:
Base(const Base&) { /*...*/ }
Base& operator=(const Base&) { /*...*/ }

};

class Derived : public Base
{
int additional_;
public:
Derived(const Derived& d)
: Base(d) // dispatch to base copy constructor
, additional_(d.additional_)
{

}

Derived& operator=(const Derived& d)
{
Base::operator=(d);
additional_ = d.additional_;
return *this;
}
};



The interesting thing is that this works even if you didn't explicitly define these functions (it then uses the compiler generated functions).



class ImplicitBase { 
int value_;
// No operator=() defined
};

class Derived : public ImplicitBase {
const char* name_;

public:
Derived& operator=(const Derived& d)
{
ImplicitBase::operator=(d); // Call compiler generated operator=
name_ = strdup(d.name_);
return *this;
}
};

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...