Class, constructor and inherance.

Rikki Cattermole via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Oct 14 21:53:11 PDT 2015


On 15/10/15 5:43 PM, holo wrote:
> Please again, any example? I'm trying to figure out how it should be
> done but i don't have any base from which i can build some solution.
>
> #!/usr/bin/rdmd
>
> import std.stdio;
>
> interface RequestResult
> {
>
>          int add (int x);
>
> }
>
> class B : RequestResult
> {
>          int add(int x)
>          {
>                  return ++x;
>          }
> }
>
> class A
> {
>          RequestResult go(int varA, int varB)
>          {
>                  return add(varA + varB);
>          }
> }
>
> void main()
> {
>          B b = new B();
>          A a = new A();
>          int x = 12;
>          int y = 15;
>
>
>          RequestResult c = A.go(x, y);
> }
>
> It even don't want to compile, but that probably not what you ware
> thinking about.
>
> [holo at ultraxps workplace]$ dmd test.d
> test.d(24): Error: undefined identifier 'add'
> test.d(38): Error: need 'this' for 'go' of type 'RequestResult(int varA,
> int varB)'
> [holo at ultraxps workplace]$

interface IA {
	IB do(int x, int y);
}

interface IB {
	int z();
}

class A : IA {
	IB do(int x, int y) {return new B(x + y);}
}

class B : IB {
	private int value;

	this(int value) {
		this.value = value;
	}

	int z() { return value; }

	void proof() {
		import std.stdio;
		writeln("proof this is B");
	}
}

void main() {
	IA a = new A();
	IB b = a.do(1, 1);
	B realB = cast(B)b;
	realB.proof();
}

b.proof() won't compile obviously, since IB does not have a proof method.

The point here is to separate out the object gained from how you go it.
So that the implementation on how to get it doesn't matter. That way it 
can be swapped at runtime without any ill effects.


More information about the Digitalmars-d-learn mailing list