### Bookstore

 Computer Math and Games in Pascal (preview) Lazarus Handbook

### Author Topic: Shared Data between Classes  (Read 311 times)

#### Weitentaaal

• Sr. Member
• Posts: 431
• Weitental is a very beautiful garbage depot.
##### Shared Data between Classes
« on: February 01, 2023, 01:57:29 pm »
Hello,

I'm facing an issue regarding Shared Data Fields. Let's hope I can explain it briefly:

I Have a Super Class and many Sub Classes. Then i have 2 Groups of which those Objects can be Part of.
However some of those Objects can be Part of both Groups. Those Objects have Data for Example Color.
The Color in group a Can be different than in group b.

I don't want to end up like this:

Code: Pascal  [Select][+][-]
1.    TSuper = class
2.       Color: TColor;
3.
4.    end;
5.
6.    TSub = class
7.       ColorForA: TColor;
8.       ColorForB: TColor;
9.    end;
10.
Lazarus: 2.0.12 x86_64-win64-win32/win64
Compiler Version: 3.2.0

#### howardpc

• Hero Member
• Posts: 4117
##### Re: Shared Data between Classes
« Reply #1 on: February 01, 2023, 02:23:01 pm »
If a subclass is part of both group A and group B what is your algorithm for determining what color the subclass should be in relation to the colors of groups A and B?

#### KodeZwerg

• Hero Member
• Posts: 1150
##### Re: Shared Data between Classes
« Reply #2 on: February 01, 2023, 02:31:26 pm »
Maybe by indexing?
« Last Edit: Tomorrow at 31:76:97 by KodeZwerg »

#### bpranoto

• Full Member
• Posts: 116
##### Re: Shared Data between Classes
« Reply #3 on: February 01, 2023, 02:47:12 pm »
Make the group as a class and move the color field into class TGroup

Code: Pascal  [Select][+][-]
1.    TGroup = class
2.      Color:TColor;
3.    end;
4.
5.    TSuper = class
6.       Group : TGroup;
7.    end;
8.
9.    TSub = class
10.      // Access the color in Group Field
11.    end;
12.

• Hero Member
• Posts: 12887
##### Re: Shared Data between Classes
« Reply #4 on: February 01, 2023, 05:43:28 pm »
Sharing data amongst controls is quite easy, but what you really ask is a contradiction in terms: It is not the same data:
Quote
The Color in group a Can be different than in group b.
That means it must at least be a copy of any initial data...

Whereas the title suggests the same data...?

So what is it?

E.g. assigning one TStrings descendant instance to both a combobox items and a listbox items or a memo lines  is sharing the same data.
Changing one will change the other too. Otherwise you need a copy. IOW a real copy vs a pointer copy.

This issue is known in computer science as deep vs shallow copy.
« Last Edit: February 01, 2023, 06:05:19 pm by Thaddy »
Who is responsable for that!! The caller or the callee.. Out! ya'll, NOW. In UTC time, please, so maybe Yesterday or tomorrow.