Method called on illegally casted object

From RAD Studio
Jump to: navigation, search

Go Up to Access Errors


A call to a method outside valid memory will cause the Method Called On Illegally Casted Object error. The following example creates an array of two someclass objects, but attempts to call the method of the third object; since arrays are zero-based, it accesses uninitialized memory.

#include <tchar.h>
#pragma hdrstop
#include<stdio.h>
#include<dir.h>
class someclass{
	int fnumber;
  public:
	int getnumber(){return fnumber;}
	void setnumber(int nw){fnumber = nw;}
	int doublev(int val){return val*2;}
	int publicalval;

};

void myf()
{
  someclass *myc = new someclass[2];
  int answ;
  answ = myc[2].doublev(5); // error
  delete[] myc;
 
}



int _tmain(int argc, _TCHAR* argv[])
{
	myf();
	return 0;
}