Re: how to use functions of base class
m0shbear <andrey.vul@gmail.com> wrote in news:4b81ed97-3a18-4c34-b77c-
dbb3f9061ec9@a26g2000vbo.googlegroups.com:
Given
struct A {
int x;
int y;
bool operator==(const A& a) const {
return (x==a.x)&&(y==a.y);
}
};
struct B : public A {
int s;
int t;
B(int u = 0, int v = 0, int w = 0, int z = 0) : A(u,v), s(w), t(z)
{ }
bool operator==(const B& b) const {
return (dynamic_cast<A&>(*this)).operator==(dynamic_cast<const
A&>(b)) &&
(s==b.s)&&(t==b.t);
}
};
This does not compile for several reasons. There are no virtual functions
around, so dynamic_cast does not work, and is not needed at all. One
could write it a bit cleaner as:
bool operator==(const B& b) const {
return A::operator==(b) && s==b.s && t==b.t;
}
If you are just inheriting implementation, then you should use private
derivation, and then I guess this design would work more or less. On the
other hand, if you use public inheritance as here, you have a danger to
compare objects of different types. e.g.
A a(1,2);
B b(1,2,3,4);
if (a==b) {//...
This comparison works, compares a to the A part of b and returns true,
what is probably not intended. To support operator== properly in publicly
derived class hierarchies one should use a private virtual function for
actual comparison and call this from the base class operator==, after
ensuring that the operands are of the same type (via typeid() or
dynamic_cast<>). But from your description it looks like that private
inheritance would suit you better, it would refuse comparison of objects
of different types automatically.
hth
Paavo
Will B::operator==(const B&) behave as intended, according to the
spec?
I'm using composition inheritance to remove duplicate code and want to
know if it's for naught.