Home >Backend Development >C++ >How Do Member Initialization Lists Work in C Constructors?

How Do Member Initialization Lists Work in C Constructors?

Susan Sarandon
Susan SarandonOriginal
2024-12-16 06:35:14574browse

How Do Member Initialization Lists Work in C   Constructors?

Member Initialization Lists in Constructors

In C , a colon followed by an expression after a constructor is part of a member initialization list. It serves two main purposes:

1. Calling Base Class Constructors

In derived classes, the member initialization list can be used to specify the arguments for calling the constructor of the base class. For example, in the following code:

class demo
{
public:
    demo(unsigned char le = 5, unsigned char default) : len(le)
    {
        // Body of the constructor
    }
};

class newdemo : public demo
{
public:
    newdemo() : demo(0, 0)
    {
        // Body of derived class constructor
    }
};

The : demo(0, 0) syntax in the newdemo constructor calls the constructor of the demo base class with arguments 0 and 0.

2. Initializing Data Members

Before executing the constructor body, the member initialization list can be used to initialize data members of the class. This is especially useful for const members that cannot be assigned in the constructor body. For example:

class Demo
{
public:
    Demo(int& val) : m_val(val)
    {
        // Body of constructor
    }

private:
    const int& m_val;
};

In this example, the : m_val(val) syntax initializes the m_val const reference data member with the value of the constructor argument val.

The above is the detailed content of How Do Member Initialization Lists Work in C Constructors?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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