Overloading comparison operators in direct private inheritance of a derived class

I have two classes. Base class:

class A
{
    int x;
public:
    A(int n):x(n){}

    friend bool operator==(const A& left, const A& right)
    {return left.x==right.x;}
};

and a derived class that inherits from A privately:

class B : private A
{
    int y;
public:
    B(int n,int x):A(x),y(n){}
    friend bool operator==(const B& left, const B& right)
    {
        if(left.y==right.y)
        {/*do something here...*/}
        else{return false;}
    }
};

I know how to compare two instances of A: I'm just member variables to each other. But how can I compare instances of B? two instances can easily have different members "x" inside their associated instances of "A", but I don't know how to compare these instances with each other.

+3
source share
1 answer

You can pass instances to A&and use the equality operator to class A:

if (static_cast<A&>(left) == static_cast<A&>(right)) {
    // ...
}
+3
source

All Articles