Thursday, January 1, 2015

Incrementing Instance Variable of Virtual Class

Problem

I had following piece of code that increments the instance variable in the parent class within the for-loop of the child class:

public virtual class ParentClass {
  public Integer mapIndex{get; set;}
}
public class ClassWithError extends ParentClass {
  


  public ClassWithError {
    Integer mapSize;
    ...
    for (mapIndex = 0; mapIndex < mapSize; mapIndex++) {
      ...
    }
    ... 
  }
  ...

}
which resulted in following error:
Unknown error: virtual class data member of the parent in for-loop

Solution

The fix is to simply create a temporary variable to do the increment and assign the value of the temporary variable to the instance variable inside the for-loop:

public virtual class ParentClass {
  public Integer mapIndex{get; set;}
}
public class ClassWithError extends ParentClass {
  


  public ClassWithError {
    Integer mapSize;
    ...
    mapIndex = 0;
    for (Integer tempIndex = 0; tempIndex < mapSize; tempIndex ++) {
      mapIndex = tempIndex;
      ...
    }
    ... 
  }
  ...

}

No comments:

Post a Comment