Skip to content

Class having itself as member

Justus

Asked Jun 8, 2008, 9:43 AM EDT2 answers
Share
LinkedInX
Hi,
i need a member of a class to be of the same type as the class itself. When i inherit the class, the member should be of the type of the inherited type.

class BaseClass { BaseClass member; }

and

class MyClass : BaseClasse { MyClass member;}

I can achieve this by making BaseClass generic:

class BaseClass<T> { T member; }

and

class MyClass : BaseClass<MyClass> {}

but is there a more elegant way?

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Mike Gold
    0

    I would probably just handle it in the constructor.  Remember that the base class member can still point to a subtype, so you just need to construct the subtype in the constructor and point it to the member.

    e.g.

    class MyClass {BaseClass Member;  MyClass(){ Member = new MyClass();}

    0
  • 0
    I would like to have it type-safe.
    0