"Jochen Zeischka" <jochen.zeischka@rug.ac.be> wrote in message
news:bgqcq4$mg$1@gaudi2.UGent.be...
Hello,
if a base class has private members and you want to define a copy
assignment
operator for one of its derived classes, is the only way to do that by
using
GetPrivates() and SetPrivates(), as demonstrated below? Or are there more
elegant solutions?
There are more elegant solutions.
class Base {
X x;
Y y;
protected:
void GetPrivates(X&, Y&) const;
void SetPrivates(const X&, const Y&);
public:
Base();
Base(const Base&);
Base& operator=(const Base&);
};
Base::Base() {
; // construction code
}
Base::Base(const Base& b) {
; // copy construction code
}
Base& Base::operator=(const Base& b) {
x = b.x;
y = b.y;
return *this;
}
void Base::GetPrivates(X& xx, Y& yy) const {
xx = x;
yy = y;
}
void Base::SetPrivates(const X& xx, const Y& yy) {
x = xx;
y = yy;
}
class Derived: public Base {
public:
Derived();
Derived(const Derived&);
Derived& operator=(const Derived&);
};
Derived::Derived(): Base() {
; // construction code for Derived
}
Derived::Derived(const Derived& d): Base(d) {
; // copy construction code for Derived
}
Derived& Derived::operator=(const Derived& d) {
X xx;
Y yy;
d.GetPrivates(xx,yy);
this->SetPrivates(xx,yy);
// further code for Derived members
return *this;
}
The way the copy assignment is done here is quite consuming, since all
private Base members are copied twice. Once in GetPrivates and once in
SetPrivates. Using pointers is not possible, because I would have to give
up
the 'const' declaration for GetPrivates, which would mean that I would
lose
it for Derived::operator=(const Derived& d) too.
I have the impression that I'm doing something simple in a complex way...
Right
Derived& Derived::operator=(const Derived& d) {
Base::operator=(d);
// further code for Derived members
return *this;
}
Thanks for any advice!
Jochen
john
.