C++: Four situations where an initializer list must be used

[C++] Several situations that must be initialized in the class initialization list

 
1. Class members are of type const 
2. Class members are reference types
#include <iostream>
using namespace std;
  class A
{
    public:
        A(int &v) : i(v), p(v), j(v) {}
        void print_val() { cout << "hello:" << i << "  " << j << endl;}
    private:
        const int i;
        int p;
        int &j;
};
 
int main(int argc ,char **argv)
{
    int pp = 45;
    A b (pp);
    b.print_val();
}

The reason:
A const object or reference can only be initialized but not assigned a value. The body of a constructor can only do assignments, not initializations, so the only chance to initialize a const object or reference is in the initialization list before the body of the constructor.
 
Initialization is called from scratch, initialization (calling the copy constructor) creates a new object; assignment (calling the assignment operator) does not create a new object, but assigns a value to an existing object.
 
3. The class member is a class type without a default constructor
#include <iostream>
using namespace std;
 
class Base
{
    public:
        Base(int a) : val(a) {}
    private:
        int val;
};
 
class A
{
    public:
        A(int v) : p(v), b(v) {}
        void print_val() { cout << "hello:" << p << endl;}
    private:
        int p;
        Base b;
};
 
int main(int argc ,char **argv)
{
    int pp = 45;
    A b (pp);
    b.print_val();
}
The reason is also that when you create an object, you need to initialize each member of the class member
 
 
4. If the class has an inheritance relationship, the derived class must call the constructor of the base class in its initialization list
#include <iostream>
using namespace std;
 
class Base
{
    public:
        Base(int a) : val(a) {}
    private:
        int val;
};
 
class A : public Base
{
    public:
        A(int v) : p(v), Base(v) {}
        void print_val() { cout << "hello:" << p << endl;}
    private:
        int p;
};
 
int main(int argc ,char **argv)
{
    int pp = 45;
    A b(pp);
    b.print_val();
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326521230&siteId=291194637