Cannot get this C++ example migrated to D

Mike Parker aldacron at gmail.com
Sun Apr 16 06:39:17 UTC 2023


On Sunday, 16 April 2023 at 05:58:39 UTC, Skippy wrote:

These lines aren't necessary:

> // ??
> int counter;
>
> // ??
> static this()
> {
>     counter = test.objCnt;
> }
>

`t1` is default-initialized, so it's null.
>     test t1, t2 = new test();

Ditto for t3. Classes are reference objects, not value objects, 
so you must explicitly instantiate instances if you want them to 
be non-null.
>     test t3;

The modified code:

```d
class test
{
   private:
     int objNo;
     static int objCnt;

   public:
     this()
     {
         objNo = ++objCnt;
     }

     ~this()
     {
         --objCnt;
     }

     void printObjNumber()
     {
         writefln("object number : %s", objNo);
     }

     static void printObjCount()
     {
         writefln("count: %s", objCnt);
     }
}


int main()
{
     test t1 = new test(), t2 = new test();

     test.printObjCount();

     test t3 = new test;
     test.printObjCount();

     t1.printObjNumber();
     t2.printObjNumber();
     t3.printObjNumber();

     return 0;
}
```


More information about the Digitalmars-d-learn mailing list