overloading operator =

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Edge{
    
public:
    Edge();
    Edge(int v1, int v2, int weight);

    int first();
    int second();
    int edgeWeight();
    
    void operator=(Edge rhs);
    bool operator<(Edge rhEdge);
    
private:
    struct AnEdge{
        int v1;
        int v2;
        int weight;
    };
    
    AnEdge theEdge;
};



Using this class, would an appropriate overload be something like this?

1
2
3
this->theEdge.v1 = rhs.v1;
this->theEdge.v2 = rhs.v2;
this->theEdge.weight = rhs.weight;


I've seen a lot of code where they create a temp object but it seems like so much work. Logically I can't imagine this not being sufficient. Also what happened to "i before e, except after c"? I just noticed sufficient breaks that rule I guess? lol
Last edited on
Your thread title suggests you are overloading the assignment operator, so it really depends on what this overloaded version is meant to do. However, judging from the argument in void operator=(Edge), it also suggests that you are not overloading but rather just implementing a good 'ol assignment operator.

For the conventional assignment operator, I would agree that:
1
2
3
4
5
6
7
8
9
10
Edge& operator=(const Edge& rhs){
//Note the form I use above that avoids creating a temporary object
//    and returns a reference to allow for operator chaining,
//    such as Edge1 = Edge2 = Edge3.
    this->theEdge.v1 = rhs.theEdge.v1;
    this->theEdge.v2 = rhs.theEdge.v2;
    this->theEdge.weight = rhs.theEdge.weight;
    //this->theEdge = rhs.theEdge; This would be okay, too.
    return *this;
}

would probably be sufficient if all you are doing is straight copying in an assignment operator.

Note that the compiler generated assignment operator would also be sufficient for something so trivial.


Random notes:
"Weight" has always been spelled "weight". The "i before e" rule has exceptions just as many other rules in the English language.
Also, there is a difference between "except" and "accept".
Last edited on
Topic archived. No new replies allowed.