I have read (here https://stackoverflow.com/a/18351550/1474291) that it is possible to store objects of derived classes that inherit the same base class in a <vector>
. To prevent Object Slicing I need to delete the move constructor, the copy constructor and the copy assignment.
NOTE: I am interested in storing the object by value and not as pointers.
I tried to compile the following code with Visual C++ 2013 and MinGW (GCC 4.8.2 and 4.9.1) but the code fails to compile. I want to do that both in C++11 by using "delete", "default" and the older way.
What is the correct way to implement that? (Do actually C++ compilers support "delete" and "default" properly yet?)
Here is my example code:
#include <iostream>
#include <vector>
using namespace std;
#if __cplusplus > 199711L
#define CPP11
#endif
class Animal {
public:
Animal() {
cout << "Making animal:";
}
virtual ~Animal() {
cout << "Send the animal home!";
}
#ifdef CPP11
public:
Animal(Animal&&) = delete;
Animal(Animal const&) = delete;
Animal& operator=(Animal&) = delete;
#else // C++98
private:
Animal(Animal const&);
Animal& operator=(Animal&);
#endif // CPP11
public:
virtual void speak() {
cout << "I am an animal!";
}
};
class Dog : public Animal {
public:
Dog() {
cout << "Making dog:";
}
virtual ~Dog() {
cout << "Send the dog home!";
}
#ifdef CPP11
public:
Dog(Dog&&) = default;
Dog(Dog const&) = default;
Dog& operator=(Dog&) = default;
#else // C++98
private:
Dog(Dog const&);
Dog& operator=(Dog&);
#endif // CPP11
virtual void speak() {
cout << "I am a dog!";
}
};
class Cat : public Animal{
public:
Cat() {
cout << "Making cat";
}
virtual ~Cat() {
cout << "Sending the cat home!";
}
#ifdef CPP11
public:
Cat(Cat&&) = default;
Cat(Cat const&) = default;
Cat& operator=(Cat&) = default;
#else // C++98
private:
Cat(Cat const&);
Cat& operator=(Cat&);
#endif // CPP11
virtual void speak() {
cout << "I am a cag!";
}
};
int main()
{
vector<Animal> animals;
for (int i = 0; 10 > i; i++) {
Dog dog;
animals.push_back(dog);
Cat cat;
animals.push_back(cat);
}
#ifdef CPP11
for (Animal& animal: animals) {
animal.speak();
}
#else
for (std::vector<Animal>::iterator currentAnimal = animals.begin();
currentAnimal != animals.end();
++currentAnimal) {
currentAnimal->speak();
}
#endif // CPP11
return 0;
}