Posts Tagged ‘return’

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);

c++ arrays memo

November 30th, 2010

1. arrays initialization

under GCC, when you create an array statically, it’s not initialized. while you create it dynamically, it’s initialized.
here is the test code:

int main () {

	int N(1000000);

	// statically created array, not initialized
	int a[N];
	for(int i = 0; i < N; ++i) {
		if(a[i] != 0) {
			cout << "a[N] is not all zero!!!" << endl;
			break;
		}
	}

	// dynamically created array, initialized
	int *b;
	b = new int[N];
	for(int i = 0; i < N; ++i) {
		if(b[i] != 0) {
			cout << "b[N] is not all zero!!!" << endl;
			break;
		}
	}
	// dynamically created array, initialized	
	int *c;
	c = new int[N]();
	for(int i = 0; i < N; ++i) {
		if(c[i] != 0) {
			cout << "c[N] is not all zero!!!" << endl;
			break;
		}
	}
}

2. return array from function

Arrays of other types are typically returned via reference:

void retArray( (int*)& p, unsigned& size )
{
	size = 4;
	p = new int[ size ];
	for (int n = 1; n < 4; n++)
		p[ n ] = n;
}