vector inheritance problem

Started by
4 comments, last by ToohrVyk 16 years, 1 month ago
Hi All: Here I have two classes:

class BaseClass{
...
};
typedef vector<BaseClass> baselist;
class ChildClass : public BaseClass{
...
};
typedef vector<ChildClass> childlist;
void algorithm(baselist alist){
...
};



That's the basic structure. I want to make childlist as a inheritance of baselist, so I can pass a childlist to the algorithm routine like:

childlist alist;
algorithm(alist);


Is there anyway I can do this please? Or if I need to define a new list class, how can I do it please? Thanks [Edited by - Asuralm on March 3, 2008 5:43:49 AM]
Asura
Advertisement
You can't. The types you are using are completely unrelated to each other. ChildClass does not even inherit from BaseClass.

If the algorithm source code will be exactly the same for both BaseClass and ChildClass you should consider making the type of the argument a template parameter.
Oh, sorry, I made a mistake, I have amended that. The ChildClass is indeed inherited from the BaseClass as:
class ChildClass: public BaseClass{}
Asura
You're not looking to have one vector derrive from another, what you want to do is pass a vector of BaseClass pointers, which point to derrived classes:

std::vector< BaseClass* > m_BaseClassCollection;m_BaseClassCollection.push_back( new DerriveClass );void foo ( const std::vector< BaseClass* >& rCollection ){}
You can, actually. Sort of.

class BaseObject;class ChildObject : public BaseObject;void doStuff(list<BaseObject*> list);vector<BaseObject*> somelist;somelist.push_back(new ChildObject());somelist.push_back(new BaseObject());doStuff(somelist);


I'd recommend using boost (boost.org) for this however!


EDIT:
Too slow.. :D
"Game Maker For Life, probably never professional thou." =)
Quote:Original post by Asuralm
Is there anyway I can do this please? Or if I need to define a new list class, how can I do it please?


This is provably impossible, because a vector of "Derived" is not a vector of "Base" and cannot be used as if it were one. I can add a "Base" to a vector of "Base", but I cannot add a "Base" to a vector of "Derived". Thus, the operation you wish to perform is impossible.

What is possible, however, is to use a read-only sequence of "Derived" as if it were a sequence of "Base" (the read-only property makes this possible). Java and C# allow this more or less natively with generics, if I remember correctly, but you can achieve a similar effect in C++ using templates:
template <typename T>void algorithm(const std::vector<T> & v){  // Code which assumes that T is derived from Base}

For additional safety:
template <typename T>void algorithm(const std::vector<T> & v,                boost::enable_if<boost::is_base_of<Base,T>::value>::type *dummy = 0){  // Code which assumes that T is derived from Base}

This topic is closed to new replies.

Advertisement