Reputation: 2907
I have a class Queue;
I have these variables defined in that class...
int head, tail;
One of the functions check if (head==tail)
, however I cannot declare head
and tail
to be equal to 0 in that function or else every time i call that function it will reset itself...
How can i declare head
and tail
to be equal to 0 without static variables...do i need to make a default constructor?
Upvotes: 0
Views: 90
Reputation: 361472
You can do that in the constructor; more specifically in the initialization-list of the constructor!
class Queue
{
int head, tail;
public:
Queue() : head(0), tail(0) {}
// ^^^^^^^^^^^^^^^^ this is called initialization-list!
};
In the initializatin-list you can initialize all your variables!
If that looks scary, you can also do this:
class Queue
{
int head, tail;
public:
Queue()
{
head = 0;
tail = 0;
}
};
But first approach is preferred, as that is initialization, and the second one is assignment!
Read this FAQ : Should my constructors use "initialization lists" or "assignment"?
Upvotes: 4
Reputation: 76908
Yes, in C++ any non-static variables have to be initialized in a method, and a good choice is the constructor (or perhaps an init()
method, depending on what you're doing)
Upvotes: 1