One of my students make me a question (which answer i know) but I think could be instructive to formulate the same question here so many people can learn about it.
The question is:
How to implement a copy assignment into a Derived class?
Consider the following class A:
class A
{
public:
A(int i1_) : i1{i1_} {}
A(const A& a) : i1{a.i1} {} // Copy constructor
A& operator=(const A& a) // Copy assignment
{
i1=a.i1;
return *this;
}
private:
int i1;
};
and you want to implement a derived class B:
class B: public A
{
public:
B(int i1_, int i2_) : A{i1_}, i2{i2_} {}
B(const B& b) : A{b}, i2{b.i2} {} // Copy Constructor
B& operator=(const B& b) // Copy Assignment
{
/* HOW TO COPY b.i1 INTO i1 HERE? */
i2=b.i2;
return *this;
}
private:
int i2;
};
Note that in the copy constructor you can write : A(b)
to copy b.i1
into the base.
Well, how you can make the same in de copy assignment?
Obviously you can not write i1=b.i1;
because i1
is a private variable.
This is a question not for experimented but for medium and novice programmers to think and learn.
Enjoy!