yazwas
yazwas

Reputation: 111

C++ operator overloading between multiple derived classes

I have a base calss and 2 derived classes. I want to implement some multiplication operator that can be used to multiply objects from both classes.

class Base
{
public:
    virtual ~Base() {}
    virtual void print() = 0;

    Base operator * (Base & b1, Base & b2) { return b1 * b2; } <---- this wont work because of pure virtual function
};

class D2;

class D1 : public Base
{
public:
    void print() { ....} 
    D1 operator * (D1 & d) {//do some operation here}
    D1 operator * (D2 & d) {//same as above...}

private:
    int i;
};

class D2 : public Base
{
public:
    void print() { ....} 
    D2 operator * (D1 & d) { ..... }
    D2 operator * (D2 & d) { ..... }

private:
    double j;
    double m;
};

This is my initial design, but I know its not going to work, so I would What would be a good design to implement this? is there a way to implement this using templates as well? Thanks!

Upvotes: 1

Views: 849

Answers (1)

Bhupesh Pant
Bhupesh Pant

Reputation: 4349

Base operator * (Base & b1, Base & b2) { return b1 * b2; } \

// This will given compilation error.

Are you trying to multiply two entirely different object from third object? Actually this does not make any sense. This function prototype is used when operator is overloaded using non-member function.

So for your class you can also use,

Base operator * (Base & b2) { return *this * b2; } 

//provided your function class is not abstract.

This is basically expanded as this->operator*(b2)

Now coming to,

D1 operator * (D1 & d) {//do some operation here}
D1 operator * (D2 & d) {//same as above...}

Why this lines? Why do you need two functions?

You can use conversion function for conversion from one type of object and vice -versa and then just one overloaded operator* could do your work.

Although, the amount of code will be almost be the same but at least that will look cleaner.

You can also use templates but for that you has to have a common implementation for operator overloading. This can be achieved using conversion function, because then you will have generic code to be implemented for operator* function.

Please let me know if I have totally misunderstood your problem or I am going in totally opposite direction.

Upvotes: 1

Related Questions