0

I'm doing a C++ implementation of Singly Linked List that I've already done in Java. The Fraction of my Java code is as follows :

class Node
{
    int info;
    Node next;
    Node()
    {
        next=null;
    }
} 
class Op
{
    Node front= null;

    void display()
    {
        Node rear=front;
        if(rear==null)
            System.out.println("List is empty");
        else
        {
            while(rear!=null)
            {
                System.out.print("["+rear.info+"|"+rear.next+"]"+"--->");
                rear=rear.next;

            }
            System.out.println();
        }
    }
}

next stores the address of the next Node in the list,
front points to the first node in the list and
rear is used to sequentially travel the list.

Below is the C++ code that I'm trying to implement :

class Node
{
    public:
    int info;
    Node *next;
    Node()
    {
        next = NULL;
    }
};
class Op
{
    public:
    Node *front = NULL; //error line.
};

int main()
{
    return 0;
}

I'm using the Turbo C++ 3.0 compiler and the error it gives is :

Cannot initialize a class member here

I'm aware that the above problem can be resolved if I use C++11 but unfortunately the code has to be in Turbo C++ 3.0. The front has to be NULL in order to check if the list id empty or not. How do I solve this issue?

Siddharth Thevaril
  • 3,722
  • 3
  • 35
  • 71

4 Answers4

1

try this :-

Class Op 
{
 public : Node *front;
 Op():front(NULL){};
};

void main()
{
    Op o  // constructor called.
    Op *op; // pointer - no constructor called.
    Op *op2 = new Op; // constructor called.

    cout << o.front; // NULL
    cout << op->front; // garbage value
    cout << op2->front; // NULL
}
egur
  • 7,830
  • 2
  • 27
  • 47
3Demon
  • 550
  • 3
  • 9
0

have you call the header files? Sometimes JAVA programmer forget to include the header files in C++. :-P

I think the line :-

public * front = NULL;

should be :-

public : NODE *front = NULL;
3Demon
  • 550
  • 3
  • 9
0

Here's one way to do it in C++:

class Op
{
public:
    Node *front;
    Op() : front(NULL) {}  // default constructor
};
egur
  • 7,830
  • 2
  • 27
  • 47
0

Initialize it in constructor:

Op() :
 front(NULL);
{}

Still it's interesting that it's not working in Turbo C++. g++ can handle it.

Michal Špondr
  • 1,337
  • 2
  • 21
  • 44