I’m having a little bit of problem with my derived class. Basically I have a super class Object and a derived class UnmovableObject. I’m trying to add a boolean variable to the derive class, so that I can later on read it and see if my objects can be moved or not. The problem I have is that I’m storing all objects (super and derived) into a list<Object> inventory. Every time I read the values from the list, I get a weird value (204) for the isFixed() method. This is the code:
//super class
#pragma once
#include "stdafx.h"
class Object{
public:
Object(); //constructor
Object(const string name, const string description); //constructor
~Object(); //destructor
private:
string nameOfObject; //the name of the room
string objectDescription; //the description of the room
};
//derived class
#pragma once
#include "stdafx.h"
#include "object.h"
//This class creates unmovable objects - the user can't pick them up.
class UnmovableObject : public Object {
public:
UnmovableObject(string name, string description);
UnmovableObject(const Object &object) : Object(object){};
bool isFixed();
private:
bool fixed;
};
//the constructor of this class takes a boolean value (by default true) - the object is fixed in this room
UnmovableObject::UnmovableObject(string name, string description) : Object(name, description){
this->fixed = true;
}
//returns false as the object is not movable
bool UnmovableObject::isFixed(){
return this->fixed;
}
//other class
list<Object> inventory;
How can I use inventory.push_back(Object/UnmovableObject); so that when I try to access the inventory I could get the correct boolean value for all of them—true for the UnmovableObject; false for the Object .
If you are wanting to find out if any of the
Objects are fixed, then you should really makeisFixed()a member of theObjectclass. Then override it in the derived class. If you do it this way, you don’t actually have to store thefixedvariable. Also, you should change your vector to be a vector of pointers toObjects.