views:

126

answers:

4

hey

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

+1  A: 

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.

Venemo
The `friend` approach is also valid: see @Reinderien's answer.
Richard Cook
@Richard - Yes, I didn't say it is not invalid. :)
Venemo
+2  A: 

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;
}
Reinderien
+1  A: 

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".

Thomas Matthews
+1  A: 

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 */
        }
};
Martin York