N
N
newuser88882020-05-11 20:28:42
C++ / C#
newuser8888, 2020-05-11 20:28:42

How to understand the class constructors and the initialization of variables in it, what is the difference?

1st option:

class Token_stream {
public:
  Token_stream() : buffer(0), full(false) {}
  void putback(Token t);
  Token get();

private:
  Token buffer;
  bool full;
};

Token_stream ts;

2nd option:
class Token_stream {
public:
  void putback(Token t);
  Token get();

private:
  Token buffer = 0;
  bool full = false;
};

Token_stream ts;

Is there any difference?
And why doesn't the constructor work like this:
class Token_stream {
public:
  Token_stream() {
    buffer = 0;
    full = false;
  }
  void putback(Token t);
  Token get();

private:
  Token buffer;
  bool full;
};

Token_stream ts;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-05-11
@newuser8888

Is there any difference?

The difference is that initialization bool full = false;is performed for any constructor that does not have a full field listed in the initialization list.
The final state of the constructed object is the same in both cases.
And why doesn't the constructor work like this:

Because the Token class does not have a default constructor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question