A
A
Alexander2020-10-14 11:12:00
C++ / C#
Alexander, 2020-10-14 11:12:00

Why does a constructor require initialization outside the body of the constructor?

there is part of the code

class stack {
public:
     explicit stack (int size = 1000) : max_len (size)
      { // тело конструктора } 
private:
     int max_len;
};


The question is, why initialize max_len (size) in the constructor call, why not in the body of the constructor itself?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Armenian Radio, 2020-10-14
@Shemapp

Because without such initialization it is impossible to:
1) Pass parameters to base classes
2) Initialize constants.
3) Have fields for which there is no default constructor
If the first one seems to be clear, then the second requires clarification. Without such initialization, all fields in the class must first be created using the default constructor, and then be initialized again in the body of the constructor. It's double work, which is not good.
In addition, for fields that do not have a default constructor, in this case, it turns out that there is no way to adequately create them not on the heap.

A
AnT, 2020-10-15
@TheCalligrapher

Weird question. In C++, there is no other way to initialize class fields in a constructor definition. There is no initialization "in the body of the constructor itself". What are you speaking about?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question