umbreLLaJYL
umbreLLaJYL

Reputation: 185

how to implement a operator use in hierarchy?

I have a Base class with several derived classes:

class Base {
private:
    long id;
public:
    Base() {}
    ~Base() {}
    Base &operator = (long temp) {
        id = temp;
        return *this;
    }
};

template <class C>
class Temp1 : public Base {
public:
    Temp1() {}
    ~Temp1() {}
    //do something;
};

template <class C>
class Temp2 : public Base {
public:
    Temp2() {}
    ~ Temp2() {}
    //do something;
};

class Executor1 : public Temp1<int> {
public:
    Executor1() {}
    ~Executor1() {}
};

class Executor2 : public Temp2<char> {
public:
    Executor2() {}
    ~Executor2() {}
};

I want those classes to support operator =.
e.g:

int main()
{
    long id1 = 0x00001111, id2 = 0x00002222;
    Executor1 exec1;
    Executor2 exec2;

    exec1 = id1;  //exec2.id = id1;
    exec2 = id2;  //exec2.id = id2;
}

I define operator = in Base whose declaration is Base &operator = (long);.

But there is a problem clearly that = doesn't work to derive classes. So I have to define operator = totally do the same thing to every Executor.

How to deal with this case in Base in a better way?

Upvotes: 3

Views: 107

Answers (1)

JulianW
JulianW

Reputation: 907

You have to pull the =-operator into the scope of the class:

class Base
{
public:
    long id;

    Base& operator=(long id)
    {
        this->id = id;
        return *this;
    }
};

class Temp2
    : public Base
{
public:
    using Base::operator=;
};

You have to pull the operator= into the scope because the implicitly generated copy operator= of Temp2 was hiding the operator= of Base. Got this hint from @Angew from's comment.

Upvotes: 6

Related Questions