I am having trouble finding a solution to my homework. Here's what I am trying to do: I have a list of objects stored into a vector. The vector, called "AvailableObjects" is declared globally.
vector<const Object*> AvailableObjects;
...
void read_obj_file(const char* filename){
ifstream infile (filename, ios::in);
while(!infile.eof()) {
char name[20];
int attribute;
int size = 0;
infile >> name >> attribute >> size;
AvailableObjects.push_back(new Object(name, attribute, size));
}
infile.close();
return;
}
After reading the objects, I need to write a function to generate a single object, and push it on to a stack of objects available to the user.
Object* generate_object(){
return AvailableObjects.at(rand_in_range(1,AvailableObjects.size()));
}
The code above is what I wanted to use. I need to randomly select one of the objects stored in the vector, and return a pointer of that object back to whatever called the function. However, this cannot be done as the objects in the vector are const Object*, not simple Object*. This is a homework assignment, so I cannot modify the const values, they prototypes must remain the same. Lastly, I will share the object class. It has a constructor dedicated to creating a new object when passed a const Object*, but I cannot make the constructor work as it is intended.
/**
* object.h
*
* Objects are immutable (read-only) once instantiated.
*/
#ifndef OBJECT_H
#define OBJECT_H
#include<string>
using std::string;
class object{
private:
string _name;
int _attribute;
int _size;
public:
// Constructor
Object(string name, int attribute, int size){
_name = name;
_attribute = attribute;
_size = size;
}
Treat(const Treat& t){
_name = t._name;
_attribute = t._attribute;
_size = t._size;
}
// Accessors
string name() const {return _name;}
int attribute()const {return _attribute;}
int size() const {return _size;}
};
#endif
And here, also, is a function displayed throughout the code that chooses a random number in a particular range.
int rand_in_range(int low, int high){
init_rand();
high < low ? throw "Invalid range." : 0 ;
int modbase = ((high+1) - low);
int ans = 0;
ans = rand() % modbase + low;
return ans;
}
Thanks for any response, I'll be actively watching this, so, should anyone have any questions, I'll be happy to reply. Again, just to summarize, I need help to get my generate_object function to return an Object* using the vector of const Object* available to me.
class objectand a constructor calledObjectand copy constructor calledTreatwon't even begin to compile correctly. Please post valid code if you want answers concerning it.