Reputation: 66
Im new to C++. I get error on the statements marked //this shows error
but its alternative (marked as but this works
). Can someone explain this please?
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
Node *next;
int data;
};
class Que
{
public:
//this shows error
/*
Node *front, *rear;
front = NULL;
rear = NULL;
*/
//but this works
Node *front = NULL, *rear = NULL;
};
Upvotes: 1
Views: 955
Reputation: 60
#define NULL nullptr
class Node
{
public:
Node* next;
int data;
};
class Que1 {
public: //Method 1 - initializer list
Node* front{ NULL }, * rear{ NULL };
};
class Que2 {
public: //Method 2 - assignment operator for initialization
Node* front = NULL, * rear = NULL;
};
class Que3 {
public: //Method 3 - initializer list at constructor
Node* front, * rear;
Que3() : front{ NULL }, rear{ NULL }
{}
};
class Que4 {
public: //Method 4 - assignment after member intialization/construction
Node* front, * rear;
Que4()
{
front = NULL;
rear = NULL;
}
};
Your assignments were not on a function's body. since you tried to initialize, I thought about showing different syntax. method 1 is the most preferred one.
Upvotes: 0
Reputation: 15551
These:
front = NULL;
rear = NULL;
are assignment statements. And this:
Node *front = NULL, *rear = NULL;
is a declaration (definition, initialization) statement using in-class initializers.
Assignment statements are not allowed to appear in the class declaration body, whereas the initialization statements are.
Upvotes: 3
Reputation: 7736
You need a function or a class constructor to initialize the class objects:
class Node
{
public:
Node *next;
int data;
};
class Que
{
public:
Que() {
Node *front, *rear;
front = NULL;
rear = NULL;
}
};
In the aforementioned code, the front
and rear
have now a storage class since they're in constructor which is acting like a function.
To clarify better, you may use the following code:
class test {
public:
int x; // declaring a variable outside of a constructor or function
x = 10; // initialization is not allowed here
}
Upvotes: 0