Mutating Algorithm
Mutating Algorithm

Reputation: 2758

Operator Overloading using friend functions in C++

I have the following Point class.

#ifndef POINT_HPP
#define POINT_HPP

#include <string>

class Point {

private:

    double m_x, m_y;

public:

    Point();
    Point(double x, double y);
    Point(const Point &p);

    ~Point();

    // selectors
    double X() const;
    double Y() const;
    std::string ToString() const;
    double Distance() const;
    double Distance(const Point &p) const;

    // modifiers
    void X(double x);
    void Y(double y);

    Point operator - () const; // Negate coordinates
    //Point operator * (double factor) const; // Scale the coordinates.
    Point operator + (const Point & p) const; // Add coordinates.
    bool operator == (const Point & p) const; // equally compare 
operator.

    Point& operator = (const Point& source);
    Point& operator *= (double factor);

    // non member function to facilitate commutative 
multiplication
    friend Point operator * (double factor, const Point & p);
    friend Point operator * (const Point & p, double factor);

};

Point operator * (double factor, const Point & p) {
    return Point(p.m_x * factor, p.m_y * factor);
}

Point operator * (const Point & p, double factor) {
    return factor * p;
}

#endif //POINT_HPP

When creating a two Point objects and attempting to perform multiplication with the implemented * operator. I get a multiple definition error. I believe that my * operator is overloaded to so that I can perform double * Point object and Point object * double in any order. Did I declare the friend functions in the incorrect place or provide implementations in the wrong place?

Upvotes: 0

Views: 524

Answers (2)

P.W
P.W

Reputation: 26800

It is allowed to define friend functions within the class. Doing so will make them inline.

From CPP reference

A function defined entirely inside a class/struct/union definition, whether it's a member function or a non-member friend function, is implicitly an inline function.

If you do this, you can avoid the multiple definition problem.

Upvotes: 2

xaxxon
xaxxon

Reputation: 19761

They need to be marked inline if the functions are defined in a header file that will be included from multiple .cpp files. Either that or move the definition (implementation) into a .cpp file. Each .cpp file that includes the header file the way it is now is creating a definition and when they are all linked together, you then have "multiple definitions"

inline Point operator * (double factor, const Point & p) {
    return Point(p.m_x * factor, p.m_y * factor);
}

inline Point operator * (const Point & p, double factor) {
    return factor * p;
}

Upvotes: 2

Related Questions