Search code examples
c++inheritanceclasscopy-constructorvirtual-copy

C++ Class Inheritance problem


Hi I have two classes, one called Instruction, one called LDI which inherits from instruction class.

class Instruction{

  protected:
    string name;
    int value;

  public:
    Instruction(string _name, int _value){ //constructor
        name = _name;
        value = _value;
    }
    ~Instruction(){}
    Instruction (const Instruction &rhs){
        name = rhs.name;
        value = rhs.value;
    }
    void setName(string _name){
        name = _name;
    }
    void setValue(int _value){
        value = _value;
    }
    string getName(){
        return name;
    }
    int getValue(){
        return value;
    }
    virtual void execute(){}
    virtual Instruction* Clone() { 
        return new Instruction(*this); 
    }
};
/////////////end of instruction super class //////////////////////////

class LDI : public Instruction{

    void execute(){
        //not implemented yet
    }
    virtual Instruction* Clone(){
        return new LDI(*this);
    }
};

Then I create a pointer of type Instruction and try to make point to a new instance of type LDI.

Instruction* ptr;
ptr = new LDI("test", 22);

I get the following compiler errors. Any ideas what I'm doing wrong?

functions.h:71: error: no matching function for call to ‘LDI::LDI(std::string&, int&)’
classes.h:54: note: candidates are: LDI::LDI()
classes.h:54: note:                 LDI::LDI(const LDI&)

Solution

  • The code: new LDI(name, val) specifically says "Call the LDI constructor with a name and val."

    There is no LDI constructor that takes name / val. In fact, I don't see a constructor for LDI at all.

    If you want to use the constructor of a base-class, here is how:

    public LDI(string _name, int _value) // Public constructor for LDI
        : Instruction(_name, _value)     // Delegate to the base-class constructor
    {
        // Do more LDI-specific construction here
    }