Nested Classes with inheritance

Salih Dincer salihdb at hotmail.com
Sun Mar 20 05:44:44 UTC 2022


On Sunday, 20 March 2022 at 01:28:44 UTC, Era Scarecrow wrote:
> Inheritance and Polymorphism is one of the hardest things to 
> grasp mostly because examples they give in other books of 
> 'objects' is so far unrelated to software that it doesn't 
> really compare. `"An object is like a book which you can read 
> and turn the page..."` but then can't tear or burn or hand to a 
> friend or put on the shelf upside down, or put your coffee on 
> top of while you surf on the web leaving a ring on the book.

You are right, difficult model yet so abeyant. Moreover, there is 
a lot of freedom given in D. I think OOP alone is not worth 5 
cents without design patterns.

For example, my codes I just wrote below is nonsense. It looks 
like a sailboat trying to navigate a windless ocean:

```d
class Year {
   int num;

   this(int year) {
     this.num = year;
   }

   auto opBinary(string op)(Year rhs)
   if(op == "-") { // Negative & Option 1a
     return new Year(this.num - rhs.num);
   }

   auto opBinary(string op)(int rhs)
   if(op == "-") { // Negative & Option 2a
     return new Year(this.num - rhs);
   }

   auto opBinary(string op)(Year rhs)
   if(op == "+") { // Positive & Option 1b
     this.num += rhs.num;
     return this;
   }

   auto opBinary(string op)(int rhs)
   if(op == "+") { // Positive & Option 2b
     this.num += rhs;
     return this;
   }

   override string toString() const {
     import std.conv;
     return num.to!string;
   }
}

void naim()
{
   import std.stdio;

   enum categoryID : ubyte {
     leader,
     champion
   }

   class Person : Year {
     string name;
     int born, age;
     categoryID cat;
     bool life;

     this(string name, int[] years, int cat) {
       super(years[1]);

       this.name = name;
       this.born = years[0];
       this.age = isDeath();
       this.cat = cast(categoryID)cat;
     }

     int isDeath() {
       return life ? super.num - born:
                          2022 - born;
     }
   }

   auto years = [ 1967, 2017 ];
   auto NaimS = new Person
        (
          "Naim Süleymanoğlu", years, 1
        );

   with(NaimS)
   {
     life = true;
     writefln("%s\n(Born %d, when he died, was %d)", name
                                                   , born
                                                   , isDeath);
   }
}

version = 1;

void main()
{
   version(1)
   {
     auto birth = new Year(1881);
     auto death = new Year(1938);

     auto print = death - birth;
     import core.stdc.stdio;

     printf("Atatürk was %d", print.num);
     printf(" years old when he died:(");
   }
   else naim();
}
```
OOP can be aggressive like a dog. I think D should be a little 
more rigid on OOP.

SDB at 79


More information about the Digitalmars-d-learn mailing list