Richard Dixie Richard Dixie - 3 months ago 35
C++ Question

C++ Inherited Structs

I am attempting to decorate a node struct in order to allow for single/double linked lists. I have the following code:

struct node
Object* obj;

struct BasicNode: node
node* next;

When I use the following code, I get an error:

node* temp = new BasicNode;
temp->obj = nl;
head = temp;

I have defined head as
BasicNode* head;

The compiler gives me the following error:
"Invalid conversion from ListAsSLL::node* to ListAsSLL::BasicNode*"
at my
head = temp

What have I done wrong? Or was I wrong to do struct inheritance?
Thank you for your time and assistance.


head is of type BasicNode. BasicNode inherits node which means that if you want to assign to head you need at least a BasicNode which isn't the case here. You need an explicit cast (known as downcasting, parent to child class) if you know temp is of type BasicNode and you want to use it:

head = static_cast<BasicNode*>(temp);

Upcasting (from child to parent class) however doesn't require an explicit cast. For example, if you made head a type of node instead, you wouldn't have to cast it. And since you are only accessing obj, this is probably what you wanted.

node* head = //something..;

//later on..
node* temp = new BasicNode;
temp->obj = nl;
head = temp;

Then later on, if you somehow still know head contains a derived object like BasicNode you can always explicitly cast it again:

BasicNode* basicNode = static_cast<BasicNode*>(head);