Rob <so***************@yahoo.comwrites:
I have these classes (elided methods):
class Base
{
public:
Base(string name) {...}
};
class Derived : public Base
{
public:
Derived(String name) : Base( name ) {...}
};
And neither of these work:
/*** ATTEMPT ONE **/
void create(std::vector<Base>& arr)
{
...
}
int main()
{
std::vector<Derivedarr;
create( arr );
}
This should be obvious why.
/*** ATTEMPT TWO **/
void create(std::vector<Base*>& arr)
You are telling the C++ compiler that create will put pointers to
instances of Base, or any subclass of Base in arr. That means
instances that are totally unrelated to Derived.
int main()
{
std::vector<Derived*arr;
create( arr );
}
Here, you're telling the C++ compiler that arr will contain only
instances of Derived, or subclasses. But how can the C++ compiler
know that create will effectively put in arr instances of Derived, and
not instances of Base, or instances of SomethingElse that is a
subclass of Base? Worse, this is not something that can be determined
at compilation time, in general. There are theorems proving that it
is impossible.
Once again, what you're wanting is a more dynamic programming language
(may I suggest humbly: Common Lisp).
That said, the stl is not the Omega of the C++ libraries. You can
program in C++ in a very different style, using different libraries,
like Lpp:
http://www.interhack.net/projects/lpp/ or even Boost::Any.
These libraries would allow you to specify a more general type of
container for the argument of create, and let you prove by yourself
that you indeed only put instances of Derived in that vector.
--
__Pascal Bourguignon__