Jonas
Jonas

Reputation: 3174

How to call an operator from a base class within the derived class?

how to call the operator* from the derived class nVect of its base class Vect?

class Vect
{

protected:
    int v1_;
    int v2_;
    int v3_;

public:
    Vect( int v1, int v2, int v3 );
    Vect( const Vect &v);
    ~Vect();
    friend const Vect operator*(Vect& v, int n);
    friend const Vect operator*(int n, Vect& v);
};


class nVect : public Vect 
{
//private 
    int pos_;
    int value_;

    void update();

public:
    nVect(int v1, int v2, int v3, int pos, int value);
    nVect(const Vect & v, int pos, int value);
    ~nVect();

    friend const nVect operator*(nVect& v, int n);
    friend const nVect operator*(int n, nVect& v);
};

Now, the compiler complains at the following code line:

const nVect operator*(nVect& v, int n)
{
    return nVect(Vect::operator*(v, n), v.pos_, v.value_);
}

error: ‘operator*’ is not a member of ‘Vect’.

What's wrong?

Thanks all! Jonas

Upvotes: 3

Views: 88

Answers (1)

Daniel Frey
Daniel Frey

Reputation: 56873

It's a free function which is declared friend of Vect, not a member function of Vect (even if it looks like a member function as it is defined within the class, but that doesn't matter here, see the FAQ for more information). You need

const nVect operator*(nVect& v, int n)
{
    return nVect(static_cast<Vect&>(v)*n, v.pos_, v.value_);
}

That said, it's weird to take a non-const reference for operator* as a caller would usually be quite suprised if you modify the argument. Also, there is no reason to return a const value, so I suggest you change the signature to:

nVect operator*(const nVect& v, int n)
{
    return nVect(static_cast<const Vect&>(v)*n, v.pos_, v.value_);
}

(and likewise for Vect::operator*)

Upvotes: 4

Related Questions