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;
10 Years
Discussion Span
Last Post by vijayan121

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

class Node{
    void *item;
    Node *next;

    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
    T item;
    Node<T>* next;

    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 ;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.