Posts Tagged ‘this’

problem of returning *this in C++

July 5th, 2011

I have a small class, in one of whose methods I want to return the instance itself so I can continue to use the instance and thus save inputting. However, “return *this” seems not working as waht I expected. The class is like this:

UndirectedGraph.h

/*
* UndirectedGraph.h
*/

#ifndef UNDIRECTEDGRAPH_H_
#define UNDIRECTEDGRAPH_H_

#include <utility>
#include <set>

using namespace std;

namespace wp {

class UndirectedGraph {
public:
UndirectedGraph(size_t n);
virtual ~UndirectedGraph();

UndirectedGraph
//void
addEdge(size_t node1, size_t node2);

private:
size_t len;
set *nbs;
};

}

 

#endif /* UNDIRECTEDGRAPH_H_ */

UndirectedGraph.cpp

/*
* UndirectedGraph.cpp
*/
#include <utility>
#include <set>
#include <iostream>
#include "UndirectedGraph.h"

using namespace std;

namespace wp {

UndirectedGraph::UndirectedGraph(size_t n) : len(n) {
std::cout << "constructor with len: " << this->len << std::endl;
for(size_t node = 0; node != n; ++node) {
nbs = new set[this->len];
}
}

UndirectedGraph::~UndirectedGraph() {
delete[] nbs;
std::cout << "destructor finished" << std::endl;
}

UndirectedGraph
//void
UndirectedGraph::addEdge(size_t node1, size_t node2) {
if(node1 >= this->len || node2 >= this->len)
throw 1;
if(node1 == node2)
throw 2;
this->nbs[node1].insert(node2);
this->nbs[node2].insert(node1);
return *this;
}

 

 

}

And in the main() function:

int main() {
UndirectedGraph g(7);
g.addEdge(0, 1).addEdge(0, 2)
.addEdge(1, 3).addEdge(1, 5);
return EXIT_SUCCESS;
}

What am I missing?

————– EDIT ————-
The solution to the problem is to return *this as a reference to itself, as below:
UndirectedGraph & addEdge(size_t node1, size_t node2);