Saturday, August 25, 2018

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...