base adjustment outside constructor

General FreeBASIC programming questions.
Post Reply
dafhi
Posts: 1641
Joined: Jun 04, 2005 9:51

base adjustment outside constructor

Post by dafhi »

Code: Select all

'' i want to randomize properties

type myRand
  as long a = rnd
  as long b = rnd
end type


'' But, error near last line:  Base Illegal outside a CONSTRUCTOR ..

type myExtend extends myRand
  as long c
  declare sub rand_me
end type

sub myExtend.rand_me '' manual call
  dim as myRand R
  Base = R
end sub
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: base adjustment outside constructor

Post by fxm »

Code: Select all

type myRand
  as long a = rnd
  as long b = rnd
end type

type myExtend extends myRand
  as long c
  declare sub rand_me
end type

sub myExtend.rand_me '' manual call
  dim as myRand R
  cast(myRand, this) = R
end sub
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: base adjustment outside constructor

Post by fxm »

More compact:

Code: Select all

type myRand
  as long a = rnd
  as long b = rnd
end type

type myExtend extends myRand
  as long c
  declare sub rand_me
end type

sub myExtend.rand_me '' manual call
  cast(myRand, this) = myRand()
end sub
dafhi
Posts: 1641
Joined: Jun 04, 2005 9:51

Re: base adjustment outside constructor

Post by dafhi »

"you cant handle the cast"
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: base adjustment outside constructor

Post by fxm »

Another possible syntax (if the subject interests one), but a little more hacking:

Code: Select all

type myRand
  as long a = rnd
  as long b = rnd
end type

type myExtend extends myRand
  as long c
  declare sub rand_me
end type

sub myExtend.rand_me '' manual call
  cast(myRand, this).constructor()  '' cast(myRand, this) = myRand()
end sub
In the above case, there is no longer creation of a new base instance then the copy of these base member fields to the initial derived instance, but only the re-construction of the base member fields of the initial derived instance.
dafhi
Posts: 1641
Joined: Jun 04, 2005 9:51

Re: base adjustment outside constructor

Post by dafhi »

i had no idea cast was so powerful. really great info
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: base adjustment outside constructor

Post by fxm »

This all works because in this type of expression, 'cast' returns a real reference, not a copy.
Post Reply