Hi,
I'm writing a general Node class in C++ right now. I don't know how to make it having an ability to carry a general object. For example, I want my Node class could carry a general Object. It might be a "Book", a "Person" or an integer. I know in Java we got a Object class could solve this problem since all the classes in Java inherited from Object class. Is there any similar solution to this problem?
Here is my Java version solution, How could I convert it into c++? Thanks.

public class Node{

    private Object item;
    private Node next;

    public Node(Object obj) {
          item = obj;
    }

    public Object getItem() {
          return this.item;
    }

    public Node getNext() {
          return next;
    }

    public void setItem(Object obj) {
          item = obj;
    }

    public void setNext(Node n) {
          next = n;
    }
}

a completely literal translation into C++ would be like this:

class Node{
private:
    void *item;
    Node *next;

public:
    Node(void *obj) : item(obj) { }
    void *getItem() const { return item; }
    Node *getNext() const { return next; }
    void setItem(void *obj) { item = obj; }
    void setNext(Node *n) {  next = n; }
};

> a completely literal translation into C++ would be like this
yes, but we can do much better in C++. be type-safe and const-correct.

template< typename T > class Node
{
  private:
    T item;
    Node<T>* next;

  public:
    Node( const T& obj ) : item(obj), next(0) {}

    T& getItem() { return item; }
    const T& getItem() const { return item; }

    Node<T>* getNext() { return next; }
    const Node<T>* getNext() const { return next; }

    void setItem( const T& obj ) { item = obj; }
    void setNext( Node<T>* n ) {  next = n; }
};

// and for a java like node,
#include <boost/any.hpp>
// http://www.boost.org/doc/libs/1_35_0/doc/html/any.html
typedef Node<boost::any> java_node ;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.