Share this post

Link to post

Share on other sites

Yes it is, generally you want all objects of types B, C, D [...] to derive from type A and an object of type A is put into the vector. You can declare any and all polymorphic methods in A, pure or not. Otherwise you'll be doing upcasting which might not be feasible, but what you need will dictate your overall design so I can't offer advice now unless we all knew what you were trying to achieve.

0

Share this post

Link to post

Share on other sites

Yeah, but only through base and derived classes as stated above, you can't have ints and doubles mixed, and there is a reason that programming languages don't provide containers that allow you to clump random data types together, a) because it would mess with the memory allocation scheme, and b) because you wouldn't be able to do things like loop through a container and perform an operation on each member, because there would be no guarantee that the operation would be valid on any one member

Share this post

Link to post

Share on other sites

Original post by ImtiazYes it is, generally you want all objects of types B, C, D [...] to derive from type A and an object of type A is put into the vector.

Correction: you store pointers-to-A in the vector. Otherwise you'll end up slicing the derived object that you're storing in the vector, because only their base-class part can be stored.

Quote:

Original post by godsenddeathand there is a reason that programming languages don't provide containers that allow you to clump random data types together, a) because it would mess with the memory allocation scheme, and b) because you wouldn't be able to do things like loop through a container and perform an operation on each member, because there would be no guarantee that the operation would be valid on any one member

Restriction #b mostly counts for statically typed languages, and some languages work around #a by storing references instead of objects.