views:

218

answers:

4

Why do I get this error in the code below?

class ST : public Instruction{
public:
ST (string _name, int _value):Instruction(_name,_value){}

    void execute(int[]& anArr, int aVal){
     //not implemented yet
     cout << "im an st" <<endl;
     anArr[value] = aVal;
    }
    virtual Instruction* Clone(){
     return new ST(*this);
    }
};



classes.h:81: error: ‘anArr’ was not declared in this scope
classes.h:81: error: ‘aVal’ was not declared in this scope
+1  A: 

Try this out :

void execute(int anArr[] , int aVal)

since You cant use array of reference .

Ashish
void execute(int[] anArr, int aVal) still gives me the same error
+4  A: 

Because the type of anArr is invalid.

Also you may be interested in using a covariant return type on your clone method. I.e. it can return a pointer to ST instead of Instruction.

Roger Pate
+4  A: 

You have a problem with the type of the first parameter of your execute function. Read this up to know more about how to pass arrays around.

dirkgently
thanks this helped
+2  A: 

If execute() is supposed to be taking an array of integers, you should probably declare it like this:

void execute(int* anArr, int anArrLength, int aVal)
{
   // ...
}

Note that there are several differences to your method:

  • anArr is passed in as a pointer to the start of the array. The client code can simply pass in the array variable name, as by definition this is equivalent to "a pointer to the start of the array".
  • anArrLength is passed in to indicate the length of the array. This is required to ensure that the execute() method doesn't access memory which is out of the bounds of the array (or what has been allocated for the array). Doing so could result in memory corruption.

You could improve the method signature above by adding a return value to indicate success or failure. This would allow the client code to detect if there have been any problems. For example:

// Returns true on success, false on failure
bool execute(int* anArr, int anArrLength, int aVal)
{
    // Get "value" through whatever means necessary
    // ...

    if (value >= anArrLength)
    {
        // Out of bounds of array!
        return false;
    }

    anArr[value] = aVal;

    // Do whatever else you need to do
    // ...

    return true;
}
LeopardSkinPillBoxHat