michalt38
michalt38

Reputation: 1203

Operators inheritance

I have the following code:

class Rectangle
{
protected:
    int a, b;
public:
    Rectangle(int a, int b) : a(a), b(b) {}
    int area() { return a*b; }
    Rectangle operator+(const Rectangle & other)
    {
        Rectangle temp(0, 0);
        temp.a = a + other.a;
        temp.b = b + other.b;
        return temp;
    }
    void operator=(const Rectangle & other)
    {
        a = other.a;
        b = other.b;
    }
};

class Square : public Rectangle
{
public:
    Square(int a) : Rectangle(a, a) {}
};

int main()
{
    Square s1(3);
    Square s2(1);
    cout << (s1 + s2).area();
    s1 = s1 + s2;
}

The cout << (s1 + s2).area(); is OK but at s1 = s1 + s2; compiler gives me an error:

no match for 'operator=' (operand types are 'Square' and 'Rectangle')

Why this line does not work?

Upvotes: 3

Views: 129

Answers (1)

Evg
Evg

Reputation: 26362

If you don't provide an assignment operator, a compiler will declare one for you. Here, a compiler generates Square::operator=(const Square&). Assignment operator from Rectangle gets hidden by this operator. You can bring Rectangle::operator= into the scope with using declaration:

class Square : public Rectangle
{
public:
    using Rectangle::operator=;

    // ...
};

Now the code compiles, but it is flawed. As noted in comments by Konrad Rudolph, Jarod42, and molbdnilo, deriving Square from Rectangle is logically wrong, as it violates the Liskov's substitution principle. You can now assign a Rectangle to a Square, and such an assignment doesn't make sense.

Upvotes: 6

Related Questions