Home > Backend Development > C++ > Where Should I Place the Member Initializer List in a C Constructor?

Where Should I Place the Member Initializer List in a C Constructor?

Susan Sarandon
Release: 2024-12-14 12:33:11
Original
350 people have browsed it

Where Should I Place the Member Initializer List in a C   Constructor?

Initializer List Placement in Constructor Definition

When defining a class constructor, it's essential to understand the role of the member initializer list. This list initializes member variables as part of the constructor definition.

As for its placement, the initializer list is part of the constructor's definition, not its declaration. This means it's not included in the header file (.h) where the class itself is declared. Instead, it resides in the source file (.cpp) where the constructor is defined.

Example Usage

Consider the following class:

class Example
{
private:
    int m_top;
    const int m_size;
public:
    Example(int size, int grow_by = 1);
};
Copy after login

In this example, the constructor is defined as follows:

Example::Example(int size, int grow_by) : m_size(5), m_top(-1)
{
    // ...
}
Copy after login

The initializer list within this constructor initializes the member variables m_size and m_top. It is crucial to include the initializer list as part of the constructor's definition in the source file (.cpp).

Therefore, the correct placement of the initializer list is within the constructor's definition, not in the header file (.h) where the class is declared.

The above is the detailed content of Where Should I Place the Member Initializer List in a C Constructor?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template