I'm relatively new to C++, and I'm hoping someone can help me resolve an issue I'm having with unique_ptr and vectors. Essentially I'm trying to use polymorphism so that I have a vector of type "Base", which is an abstract class (pure virtual). I'm then attempting to fill this vector with derived classes. I've included a trivial example below, showcasing exactly what I'm trying to achieve. Please note that I need to use C++11, which is why I haven't made use of "std::make_unique". The code compiles fine, but I get run-time errors about "default_delete" in class Animal.
A related question is should I be using unique_ptrs for run-time polymorphism as below? Or should I be using raw pointers instead?
Header file and CPP files below. Error output from VS is included below this. Very many thanks in advance for any help with this.
HEADER FILE:
#ifndef START_H
#define START_H
#include
#include
class Animal
{
public:
virtual ~Animal() = default;
void run();
void setNumLegs(int a) { numLegs = a; }
const int getLegs() const { return numLegs; }
private:
double numLegs;
virtual void useLegs() = 0;
};
class Biped : public Animal
{
private:
void useLegs();
};
class Multiped : public Animal
{
public:
double costOfShoes{ 12.0 };
private:
void useLegs();
void payForShoes();
void becomeDestitute();
};
class Farm
{
public:
std::vector> animals;
};
class Countryside
{
public:
std::vector> farms;
};
#endif // START_H
CPP FILE:
#include "start.h"
#include
int main() {
Countryside countryside;
std::unique_ptr f(new Farm);
std::vector legs = { 2,4,5,2,10 };
for (auto& numLegs : legs) {
if (numLegs == 2) {
std::unique_ptr biped(new Biped);
biped->setNumLegs(numLegs);
f->animals.push_back(std::move(biped));
}
else if (numLegs > 2) {
std::unique_ptr multiped(new Multiped);
multiped->setNumLegs(numLegs);
f->animals.push_back(std::move(multiped));
}
}
countryside.farms.push_back(std::move(f)); //THIS IS WHERE THE PROBLEM IS I THINK
for (auto& animal : f->animals) {
animal-> run();
}
return 0;
}
void Animal::run()
{
useLegs();
}
void Biped::useLegs()
{
std::cout << "Running with: "<< getLegs() <<"legs\n";
}
void Multiped::useLegs()
{
std::cout << "Running with many legs:" << getLegs() << "!!! legs\n";
payForShoes();
}
void Multiped::payForShoes()
{
std::cout << "Paying for shoes...\n";
becomeDestitute();
}
void Multiped::becomeDestitute()
{
std::cout << "I have no money left.\n";
}
DEBUGGER ERROR OUTPUT:
_Mypair <struct at NULL> std::_Compressed_pair>>,std::_Vector_val>>>,1>
_Mypair._Myval2 std::_Vector_val>>>
this 0x00000000 std::vector>,std::allocator>>> *
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)