In ch 6 "Writing a program",
what is the use of the function Token_stream(); inside that class? Dont we make a token stream by saying" Token_stream ts; ". What is that unknown function doing inside?
By the way, should I give more info?
1 2 3 4 5 6 7 8
class Token_stream {
public:
Token_stream(); // make a Token_stream that reads from cin
Token get(); // get a Token
void putback(Token t); // put a Token back
private:
// implementation details
};
That is the function that gets called when you create a Token_stream object. The code you have above is the declaration of it; somewhere else should be the implementation.
The functions that get called to create an object are known as its constructors. The constructor that takes no parameters (like this one) is known as the default constructor.
If you do not create a default constructor yourself, a simple one is made for you without you having to worry about it.
The use of writing it is so that you can control what happens when the object is created. For example, you could set internal variable values.
Dont we make a token stream by saying" Token_stream ts; ". What is that unknown function doing inside?
Yes, we do. This is the function that gets called when you say "Token_stream ts;"
Once you get into making decent classes, you'll find the constructors to be absolutely vital. It is important that you understand what they are.
class Token_stream {
public:
Token_stream(); // make a Token_stream that reads from cin
Token get(); // get a Token (get() is defined elsewhere)
void putback(Token t); // put a Token back
private:
bool full; // is there a Token in the buffer?
Token buffer; // here is where we keep a Token put back using putback()
};
***
1 2 3 4
Token_stream::Token_stream()
:full(false), buffer(0) // no Token in buffer
{
}
this code is part of error correcting exercise in the book. So why does the {} come after :full(false), buffer(0)? Is it a error?
Is this the implementation? If so, what does the 0 inside buffer mean?
Thanks for the quick reply!