Originally Posted by
Ñuño Martínez
If descendant classes use the same data than the parent ones then there's no problems. I see it. The problem is how to know which typecast to use.
Unless you want to dynamically switch an array member between types, then you can just call the adequate constructor when creating the member and it will work fine.
Code:
program aaa; {$MODE OBJFPC}
type bbb = object
public procedure hello; virtual;
public constructor create;
public destructor destroy; virtual;
end;
type ccc = object(bbb)
public procedure hello; virtual;
public destructor destroy; virtual;
end;
procedure bbb.hello;
begin
writeln('bbb: hello')
end;
constructor bbb.create;
begin
writeln('bbb: create')
end;
destructor bbb.destroy;
begin
writeln('bbb: destroy')
end;
procedure ccc.hello;
begin
writeln('ccc: hello')
end;
destructor ccc.destroy;
begin
writeln('ccc: destroy')
end;
Var
X: Array[0..1] of bbb;
begin
X[0].Create();
ccc(X[1]).Create();
X[0].Hello();
X[1].Hello();
X[0].Destroy();
X[1].Destroy()
end.
Although the compiler says that "X is not initialized" during "X[0].Create()", the above code (with FPC 2.6.4) works fine - after the constructors are called, the VMT pointers are set up, so calls to Hello() and Destroy() are properly resolved to those of the child class:
Code:
bbb: create
bbb: create // "ccc" did not have an explicit constructor, so the "bbb" constructor was called, but the VMT is still set up properly
bbb: hello
ccc: hello
bbb: destroy
ccc: destroy
IMO, with what you're trying to achieve, it would actually be simpler to just use records and have a "spriteType" field there. You can use the Case() statement to test for the type and call the appropriate procedure when needed. It may not look the prettiest, but it's the simplest way and there's no risk that compiler optimisations mess something up.
Also, you can have a SPRITETYPE_NONE value for your spriteType, which gives you a way to have "NULL" array members for free.
Also, have you tried using a profiler? It may turn out that the memory accesses aren't really that much of a problem and you're trying to optimize the wrong thing.
Bookmarks