Converting multiple inheritance code into C ++ for D language

biozic via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 18 08:27:51 PST 2017


On Saturday, 18 February 2017 at 12:56:51 UTC, wiki wrote:
> On Saturday, 18 February 2017 at 09:33:25 UTC, biozic wrote:
>> A mixin can be used to provide an base implementation for the 
>> methods of an interface, along with data members, so that you 
>> don't have to define it in every class that implements the 
>> interface.
>>
>> An example : https://dpaste.dzfl.pl/b656851e5c51
>
>
>
> I tried to use it in the same way but I did not understand 
> correctly because to simulate, alias in this code I had already 
> defined the classes as interfaces but I did not understand how 
> these constructors should be declared for later use ..

There are multiple typos problems with your code. For me, the 
main problem would be that this code is using OOP the wrong way, 
but maybe this code doesn't represent what you actually want to 
do... Anyway, see a corrected version below.

import std.stdio;

class Test1
{
     protected string _msg1;

     this(string msg1)
     {
         _msg1 = msg1;
     }
} // No semicolon

interface Test2
{
     // Interfaces can't have data members

     // This template could actually be out of the interface.
     // I just put it here because it's more clear that it's 
related to Test2.
     mixin template Impl()
     {
         protected string _msg2; // Data member is inside the 
template

         // This function is not a constructor. Only the class 
implementing
         // the interface will have one.
         void thisTest2(string msg2)
         {
             _msg2 = msg2;
         }
     }
}

interface Test3
{
     mixin template Impl()
     {
         protected string _msg3;
         void thisTest3(string msg3)
         {
             _msg3 = msg3;
         }
     }
}

class Test4 : Test1, Test2, Test3
{
     mixin Test2.Impl;
     mixin Test3.Impl;

     string _msg4;

     this(string msg1, string msg2, string msg3, string msg4)
     {
         super(msg1);  // Calls the constructor of Test1
         thisTest2(msg2); // Use interface Test2
         thisTest3(msg3); // Use interface Test3
         this._msg4 = msg4; // Test4 implementation
     }

     void show() // Don't use override here
     {
         writeln(_msg1, _msg2, _msg3, _msg4);
     }
}

void main()
{
     auto teste = new Test4("\n\tTeste1 ", "Teste2 ", "Teste3 ", 
"Teste4");
     teste.show();
     // No explicit return is required
}


More information about the Digitalmars-d-learn mailing list