srilakshmikanthanp
srilakshmikanthanp

Reputation: 2399

How to access overloaded operator in base class from derived class?

See the following code:

#include<iostream>

using namespace std;


class ex
{
    int i;
public:
    ex(int x){i=x;}
    void operator-()
    {
        i=-i;
    }
    int geti(){return i;}
};

class derived:public ex
{
    int j;
public:
    derived(int x,int y):ex(x){j=y;}
    void operator-()
    {
     j=-j;
    }
    int getj(){return j;}
};


int main()
{
    derived ob(1,2);
    -ob;
    cout<<ob.geti();
    cout<<"\n"<<ob.getj();
}

output:

1
-2
Process returned 0 (0x0)   execution time : 0.901 s
Press any key to continue.

I define the - operator in both the base and derived classes, but -ob; calls only the operator of the derived class. So how to also change the i field to -i (calling the operator in the base class).

Do I need any explicit function to achieve this?

Upvotes: 2

Views: 887

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311176

It seems you mean

void operator-()
{
    ex::operator -();
    j=-j;
}

In any case it would be better to declare the operators like for example

ex & operator-()
{
    i = -i;

    return *this;
}

and

derived & operator-()
{
    ex::operator -();

    j = -j;

    return *this;
}

You could also make the operator virtual. For example

#include<iostream>

using namespace std;


class ex
{
    int i;
public:
    virtual ~ex() = default;

    ex(int x){i=x;}
    virtual ex & operator-()
    {
        i = -i;

        return *this;
    }

    int geti(){return i;}
};

class derived:public ex
{
    int j;
public:
    derived(int x,int y):ex(x){j=y;}
    derived & operator-() override
    {
        ex::operator -();

        j = -j;

        return *this;
    }
    int getj(){return j;}
};


int main()
{
    derived ob(1,2);

    ex &r = ob;

    -r;

    cout<<ob.geti();
    cout<<"\n"<<ob.getj();
}    

Upvotes: 5

Eduardo Fernandes
Eduardo Fernandes

Reputation: 403

Your derived class could be declared like this:

class derived:public ex
{
    int j;
public:
    derived(int x,int y):ex(x){j=y;}
    void operator-()
    {
        j=-j;
        ex::operator-();
    }
    int getj(){return j;}
};

Upvotes: 1

Related Questions