I have two different classes (First, Second) which inherit the same base class (Base). I would like to store an instance of First and Second in the same vector, without their classes being spliced down to the Base class. If I use vector, this splicing will occur, like following:
#include <iostream>
#include <vector>
class Base {
public:
Base() { }
virtual void test() { std::cout << "I am just the base class\n"; }
};
class First : public Base {
public:
First() { }
void test() { std::cout << "This is the First class\n"; }
};
class Second : public Base {
public:
Second() { }
void test() { std::cout << "This is the Second class\n"; }
};
int main() {
First *f = new First();
Second *s = new Second();
// First, I keep a vector of pointers to their base class
std::vector<Base> objs;
objs.push_back(*f);
objs.push_back(*s);
objs[0].test(); // outputs "I am just the base class"
objs[1].test(); // outputs "I am just the base class"
}
Ultimately, when the two objects are put in to vector, they are spliced. Is there a way (without boost) to COPY both of these objects in to the same vector? A vector is not what I am looking for, I want to copy the objects.
There were a lot of good answers here. Unfortunately, I can't assume C++11, so I ended up leveraging the clone constructor with the hint at storing pointers. But ultimately, the clone allows me to create the copy first.
Here was my final solution:
#include <iostream>
#include <vector>
class Base {
public:
Base() { }
virtual void test() { std::cout << "I am just the base class\n"; }
virtual Base* clone() const = 0;
};
class First : public Base {
public:
First() { }
void test() { std::cout << "This is the First class\n"; }
First* clone() const { return new First(*this); }
};
class Second : public Base {
public:
Second() { }
void test() { std::cout << "This is the Second class\n"; }
Second* clone() const { return new Second(*this); }
};
int main() {
First *f = new First();
Second *s = new Second();
std::vector<Base *> bak;
bak.push_back(f->clone());
bak[0]->test();
}