[ create a new paste ] login | about

Link: http://codepad.org/weUsTlSe    [ raw code | output | fork ]

C++, pasted on May 2:
#include <cstdlib>
#include <iostream>
using namespace std;

class Runnable
{
public:
	virtual int operator()()
	{
		cerr << "FATAL: operator() not implemented for instance of Runnable." << endl;
		exit(EXIT_FAILURE);
	};
};

class Return : public Runnable
{
private:
	int i;

public:
	Return(int i)
		: i(i)
		{}
	
	int operator()()
	{
		return i;
	}
};

int callRunnable(Runnable *r)
{
	return r->operator()();
	// or return (*r)();
}

int main()
{
	Return r(42);
	cout << callRunnable(&r) << endl;
	
	Runnable &s = r;
	cout << callRunnable(&s) << endl;
	
	// Does not work: assignment discards subclass information.
	Runnable t = r;
	cout << callRunnable(&t) << endl;
	
	return 0;
}


Output:
1
2
3
42
42
FATAL: operator() not implemented for instance of Runnable.


Create a new paste based on this one


Comments: