i am a new programer in c++
and i have an abstract class A, and i implemented operators in it.
and now i have two classes B and C that extend A.
for some reason the compiler does not identify the operators.
is it because that operators are not inherrited? or is it because that i have a code bug?
here is the code:
#ifndef A_
#define A_
class A{
public:
friend bool operator==(const A &a1,const A &a2);
}
#endif
inline bool operator==(const A& a1, const A& a2){
....
}
is it not meant to work on B==C and B==B and C==C? thanx
Matt
4 Answers 4
The program compiles and runs as expected, correctly calling the right operator when I try it:
class A {
public:
friend bool operator==(const A &a1, const A &a2);
};
bool operator==(const A &a1, const A &a2) {
return false;
}
class B : public A {};
class C : public A {};
int main()
{
B b;
C c;
bool equals = b == c;
return 0;
}
Comments
Put the operator inside the class.
#ifndef A_
#define A_
class A
{
...
public:
bool operator==(const A &other)
{
// your operator logic
}
}
#endif
Optionally, you could make it virtual thus allowing you to override it in the derived classes.
2 Comments
friend approach is also valid: see @Reinderien's answer.My suggestion: don't overload comparison operators in base classes, but implement equivalent protected methods. This will prevent some hard to detect failures in your program.
Example:
class Base
{
protected:
bool equal_base(const Base& other) const
{ return member == other.member;}
private:
unsigned int member;
};
class B_Child : public Base
{
public:
bool operator==(const B_Child& other) const
{ return (member_b == other_member_b) && equal_base(other);}
private:
std::string member_b;
};
class C_Child : public Base
{
public:
bool operator==(const C_Child& other) const
{ return (member_c == other_member_c) && equal_base(other);}
private:
double member_c;
};
Also search the web for "C++ virtual equality operator".
Comments
How about:
class A
{
public:
bool operator==(A const& rhs) const
{
return this->isEqual(rhs);
}
private:
virtual bool isEqual(A const& rhS)
{
return /* Your test here */
}
};
class B: public A
{
private:
virtual bool isEqual(A const& rhS)
{
B& theRealRHS = dynamic_cast<B const&>(rhs); // Throws if it is not a B
return /* Your test here */
}
};
Bis passed to a function that operates on objects of typeA, there is no easy process for the function to differentiate between an instance ofBorC. Very bad design when using generic programming. Many of my early programs failed because of this.inline bool operator==outside the include guard looks a bit suspicious.