Inheritance info lost in container?

Code mostly speaks for itself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <list>
#include <iostream>
using namespace std;

struct mybase{
	virtual void proc(){
		cout << "I'm mybase" << endl;
	}
};

struct myderiv: public mybase{
	void proc(){
		cout << "I'm myderiv" << endl;
	}
};

int main(){
	myderiv a;
	a.proc();

	mybase *b = &a;
	b->proc();

	list<mybase> c;
	c.push_back(a);
	list<mybase>::iterator it = c.begin();
	(*it).proc();

	return 0;
}
I'm myderiv
I'm myderiv
I'm mybase


I added an object of class myderiv to the container, but when I retrieve it back and try to manipulate it, it's actually of class mybase. Is there any way to keep the inheritance information in the container?
a list of mybases is always a list of mybases, it can't hold a myderived.

To store runtime-polymorphic object handles in a container, you could have a list of pointers to mybase, e.g std::list<std::unique_ptr<mybase>>

online demo: http://ideone.com/aglx9w

PS: you forgot a virtual destructor in your base class
How would this be done pre-C++11?
The only C++11 code in Cubbi's snippet is the unique_ptr smart pointer, which is also available in the Boost library.

The point is that you need to store pointers to the base class.
I know that, how would it be done with pre-C++ STL?
Last edited on
std::list<mybase *>
No STL? No containers at all? Well, there are regular arrays and dynamic arrays.
1
2
mybase** b_ptrs(NULL);
mybase* b_ptrs2[N]; //Where N is some constant 
Pre-C++11 but with STL. I believe raw pointers would result in memory leaks when they're erased. Cuz I'm new'ing them.
Last edited on
Then keskiverto's code snippet would work fine.

Raw pointers only result in a memory leak if you forget to call delete for every new.
Topic archived. No new replies allowed.