IonicWind Software

Aurora Compiler => Tips and Tricks => Topic started by: sapero on January 15, 2007, 11:42:28 AM

Title: How to add methods to structure
Post by: sapero on January 15, 2007, 11:42:28 AM
In C++, defining a class without virtual methods - the class will have same size as the sum of private variables sizes. In Aurora this is impossible, always a DWORD is added that points to jumptable, so how to add methods to struct?

Maybe you do not know, but redefining a structure is just ignored, without warnings.
struct s_A {int a;}
struct s_A {int b;} // no error, just ignored
s_A x;
print(x.b); // error: b is undefined; so the second definition of s_A was ignored


I've got an idea to redefine structure creating a class with same name, and it worked!
#autodefine "OFF"
// standard RECT structure is defined as follows:
struct RECT
{
int left;
int top;
int right;
int bottom;
}
// declaring a class with same name as structure - the class will be ignored,
// but methods are accepted. The "RECT" token was declared first as structure,
// second definition is ignored without warnings :)
class RECT
{
// define some common methods
declare Set(int l,int t,int r,int b);
declare Width(),int;
declare Height(),int;
}

// now we can test it:
sub main()
{
RECT rc;
openconsole();
print("sizeof RECT = ", sizeof(RECT)); // 16
print("not initialized RECT values: ", rc.left,",",rc.top,",",rc.right,",",rc.bottom);

// initialize RECT and display new contents
rc.Set(1,1,100,200);
print("initialized RECT values: ", rc.left,",",rc.top,",",rc.right,",",rc.bottom);
print("the width is ", rc.width());
print("the height is ", rc.height());

print("\npress any key to quit");
FreeHeap(readln());
}



RECT::Set(int l,int t,int r,int b)
{
// this will produce an error, the class has no variables!:
left = l;
// instead we should cast variables to struct
*(RECT)this.left = l;
*(RECT)this.top = t;
*(RECT)this.right = r;
*(RECT)this.bottom = b;
}

RECT::Width(),int
{
return *(RECT)this.right - *(RECT)this.left;
}

RECT::Height(),int
{
return *(RECT)this.bottom - *(RECT)this.top;
}
Title: Re: How to add methods to structure
Post by: Kale on January 15, 2007, 12:02:40 PM
Is this intended behaviour? Lol! Nice find! :D
Title: Re: How to add methods to structure
Post by: Steven Picard on January 15, 2007, 04:09:41 PM
Cool find!