D style - member functions

H. S. Teoh hsteoh at qfbox.info
Wed Apr 26 18:32:52 UTC 2023


On Wed, Apr 26, 2023 at 06:24:08PM +0000, DLearner via Digitalmars-d-learn wrote:
> Consider:
> ```
> struct S1 {
>    int A;
>    int B;
>    int foo() {
>       return(A+B);
>    }
> }
> 
> struct S2 {
>    int A;
>    int B;
> }
> int fnAddS2(S2 X) {
>    return (X.A + X.B);
> }
> 
> void main() {
>    import std.stdio : writeln;
> 
>    S1 Var1 = S1(1, 2);
>    writeln("Total Var1 = ", Var1.foo());
> 
>    S2 Var2 = S2(1, 2);
>    writeln("Total Var2 = ", fnAddS2(Var2));
> 
>    return;
> }
> ```
> 
> Of the two ways shown of producing the total from the same underlying
> structure, which is the better style?

Either way works, it doesn't really matter.  The slight difference is
that the member function is preferred when resolving a symbol, so if
there's a module-level function called `foo` that takes S1 as a
parameter, the member function would be called instead.


> Further, do we care about the situation where there are many variables
> of type 'S', which presumably means the function code generated from
> S1 gets duplicated many times, but not so with S2?

This is false. Member functions are only instantiated once in the entire
program, not with every instance of S.

(Template functions may be instantiated more than once, but that's still
only once per combination of template arguments, not once per instance
of the enclosing type.)


T

-- 
MAS = Mana Ada Sistem?


More information about the Digitalmars-d-learn mailing list