I’ve clearly been stuck in Java land for too long… Is it possible to do the C++ equivalent of the following Java code:
interface Foo {}
class Bar implements Foo {}
static List<Foo> getFoo() {
return new LinkedList<Foo>();
}
static List<Bar> getBar() {
return new LinkedList<Bar>();
}
List<? extends Foo> stuff = getBar();
Where Foo is a sub-class of Bar.
So in C++….
std::list<Bar> * getBars()
{
std::list<Bar> * bars = new std::list<Bar>;
return bars;
}
std::list<Foo> * stuff = getBars();
Hope that makes sense….
No in my opinon that does not make sense in C++.
First you return a reference that does not exist anymore. To avoid this, you can pass your std::list as a reference parameter to be modified in the function, as
Second, foos are not bars and can’t be copied one to another, except I think if you provide the right copy operator.
But if you use inheritance, all your foos and bars should be pointers (and if you can smart ones as shared_ptr pointers from boost or tr1). But that doesn’t mean the copy works.
I’m not really sure about what you want to do, but transposing from JAVA to C++ in this case does not work. If you create foos, they will have everything from bars automatically.
If you want a list of bars constructed as foos:
Or as I would put it in real C++ code with shared_ptr: