Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad form to refer to a derived type in a base type?

I have a category/file tree structure. Both categories and files can have parents, so I derived them from a common base class that has a Parent property. Since all parents will obviously always be categories (files can't be a parent), it seems to make sense to make the Parent property of the node be the CategoryNode type.

Is it bad form for the base class to refer to the derived class? If so, why? What's a better way to structure this, if so?

class Node {
    public CategoryNode Parent {get; set;}
}

class File : Node {
    ...
}

class CategoryNode : Node {
    ...
}
like image 815
Kelsie Avatar asked Jul 03 '12 07:07

Kelsie


People also ask

Can a derived class reference to base class object?

No. A reference to a derived class must actually refer to an instance of the derived class (or null).

Why can't a derived pointer reference a base object?

similarly a derived object is a base class object (as it's a sub class), so it can be pointed to by a base class pointer. However, a base class object is not a derived class object so it can't be assigned to a derived class pointer.

Can base class access derived members?

// As base-class pointer cannot access the derived class variable.

Can a derived pointer point to a base class?

Derived class pointer cannot point to base class.


1 Answers

You could do ...

interface IParent {
    ...
}

class Node {
    public IParent Parent {get; set;}
}

class File : Node {
    ...
}

class CategoryNode : Node, IParent {
    ...
}

This way, you don't need to refer to a derived object in the base class, plus, you're more flexible in what can actually become a parent, in case you get additional object types at a later point in time. Also, any functionality that is relevant just for a parent can be declared in that interface.

like image 77
takrl Avatar answered Oct 19 '22 22:10

takrl