Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading comparison operators in derived class right private inheritance

I've got two classes here. A 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 just the member variables to each other. But how can I possibly compare instances of B? two instances could easily have different "x" members inside their associated "A" instances, but I have no idea how to compare those instances to each other.

like image 842
Alexander Questioning Bresee Avatar asked Dec 03 '25 18:12

Alexander Questioning Bresee


1 Answers

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

if (static_cast<A&>(left) == static_cast<A&>(right)) {
    // ...
}
like image 148
Jon Avatar answered Dec 05 '25 09:12

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!