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

How Do Member Initialization Lists Work in C Constructors?

Susan Sarandon
Release: 2024-12-16 06:35:14
Original
568 people have browsed it

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
    }
};
Copy after login

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;
};
Copy after login

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!

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