Search code examples
c++classnew-operator

C++ new operator. Creating a new instance


I'm having some trouble creating an object in C++. I create a class called Instruction, and I am trying to create a new instance, but I get compiler errors.

Class code:

class Instruction{

  protected:
    string name;
    int value;

  public:
    Instruction(string _name, int _value);
    ~Instruction();
    void setName(string _name);
    void setValue(int _value);
    string getName();
    int getValue();
    virtual void execute();
};



//constructor
inline Instruction::Instruction(string _name, int _value){
    name = _name;
    value = _value;
}
//destructor
inline Instruction::~Instruction(){
    //name = "";
    //value = 0;
}
inline void Instruction::setName(string _name){
     name = _name;
}

inline void Instruction::setValue(int _value){
    value = _value;
}

inline string Instruction::getName(){
       return name;
}

int Instruction::getValue(){
    return value;
}
inline void Instruction::execute(){
    cout << "still have to implement";
}

This is how I try to create a new object:

Instruction* inst;
inst = new Instruction("instruction33", 33);

I get the following compiler errors:

functions.h:70: error: no matching function for call to ‘operator new(unsigned int, std::string&, int&)’
/usr/include/c++/4.3/new:95: note: candidates are: void* operator new(size_t)
/usr/include/c++/4.3/new:99: note:                 void* operator new(size_t, const std::nothrow_t&)
/usr/include/c++/4.3/new:105: note:                 void* operator new(size_t, void*)

You guys are correct. The error comes from this line of code:

instList.push_back(inst);

where instList is created like this:

list <Instruction> instList;  //#include <list> is in the file

Solution

  • inst is a pointer to an Instruction object and instList is a list of Instruction objects. So when you try instList.push_back(inst) it doesn't work (it expects a real object not the pointer to it). You should instead have instList.push_back(*inst).