0

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 
2
  • Modifying the code a bit (i.e. getting rid of Instruction), I get a different error on the same line and that's with the syntax. What compiler are you using? Commented Nov 18, 2009 at 6:32
  • 2
    @unknown: just to ensure, is the code pasted above in classes.h? and which of these lines is 81? is it the line with the "void execute" Commented Nov 18, 2009 at 6:37

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

1

Try this out :

void execute(int anArr[] , int aVal)

since You cant use array of reference .

1 Comment

void execute(int[] anArr, int aVal) still gives me the same error
1

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.