Question

If you have a generic Node that store ints, float or Objects of a certain type, how could you store generic objects in your node?

typedef struct node{
      Dog data;
      node* next;
  }*nodePtr;

This node stores Dog objects... how could I store generic objects?

One idea I have is to have Dog objects and all other objects inherit from a more general Object class. Good way to go other than using templates?

Était-ce utile?

La solution 3

One idea I have is to have Dog objects and all other objects inherit from a more general Object class. Good way to go?

If the types all have something in common, create a common base type for them. If not, then don't.

Don't make the types derive from a common base just because you want to store them all in the same container. You'd have it backwards. If you want to store all the types in the same container, they should have something in common already. Otherwise your container is just a sequence of bits. There would be nothing it could do that wouldn't be better done by separate containers for each type. For example, you couldn't iterate through the container and call a method on each element, because there wouldn't be a method that all the elements have!

You said,

Great answer, but I'm looking to do it through OO principles.

One of the basic principles of OO, IMO, is that all your classes should be meaningful. This doesn't mean they have to correspond to concrete objects, or even contain any implementation, but they do have to at least contain some interface. A generic Object class in C++ is not meaningful. Don't create one.

Autres conseils

C++ offers the template<> for generics:

template<typename T>
struct node {
    T data;
    node<T> *next;
}

Make a template, like this:

template<typename T>
struct Node
{
    T data;
    Node<T> *next;
};

A good resource to find information on templates can be e.g. the Wikipedia.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top