How to declare a virtual member (not a function) in a class

Simen Kjærås simen.kjaras at gmail.com
Tue Feb 18 12:54:19 UTC 2020


On Tuesday, 18 February 2020 at 12:37:45 UTC, Adnan wrote:
> I have a base class that has a couple of constant member 
> variables. These variables are abstract, they will only get 
> defined when the derived class gets constructed.
>
> class Person {
>     const string name;
>     const int id;
> }
>
> class Male : Person {
>     this(string name = "Unnamed Male") {
>         static int nextID = 0;
>         this.id = nextID++;
>         this.name = name;
>     }
> }
>
> The compiler restricts me from assigning those two functions. 
> How can I get around this?

const members can only be set in the constructor of the type that 
defines them. To set them in a subclass, forward the values to 
the superclass' constructor:

class Person {
     const string name;
     const int id;
     protected this(string _name, int _id) {
         id = _id;
         name = _name;
     }
}

class Male : Person {
     this(string name = "Unnamed Male") {
         static int nextID = 0;
         super(name, nextID++);
     }
}

--
   Simen


More information about the Digitalmars-d-learn mailing list