Why do we use colons (:) in constructors?

Asked 1 years ago, Updated 1 years ago, 79 views

I saw a code like this

#include <iostream>

class Foo {
public:
  int bar;
  Foo(int num): bar(num) {};
};

int main(void) {
  std::cout << Foo(42).bar << std::endl;
  return 0;
}

What is written here like : bar(num)?

I've never seen him wear it like that Are you calling another function? Or is it related to the constructor if you look at what the constructor wrote?

c++ syntax constructor ctor-initializer

2022-09-22 22:25

1 Answers

Foo(int num): bar(num) is called an initialization list and serves to initialize the member variable bar to num.

// initialization list
Foo(int num): bar(num) {};

//Initialize in function
Foo(int num)
{
   bar = num;
}

Just constructor function {} It's an internal initialization, and it's an internal initialization The difference between writing the initialization list like this is

When you initialize from an initialization list, the object is created and initialized at once when the constructor is called.

If you initialize in {} in the constructor function, the object is created and assigned once again with the default constructor initialized. In this case, you go through the second stage of default allocation-user allocation, resulting in overhead.

The following are the main situations in which you have to write an initialization list:

For example,

class MyClass
{
    public:
        int &i; // Reference Member. Need to write initialization list
        int b;
        //Nonstatic const member. Need to write initialization list
        const int k;  

    //The name of the constructor parameter is the same as the data member. Allows writing of the initialization list (selectable)
    MyClass(int a, int b, int c):i(a),b(b),k(c)
    {
        /*
        If you don't want to write an initialization list
        this->a = a
        Must be shared
        */
    }
};

class MyClass2:public MyClass
{
    public:
        int p;
        int q;
        //The base class MyClass must be initialized in the initialization list because there is no default generator
        MyClass2(int x,int y,int z,int l,int m):MyClass(x,y,z),p(l),q(m)
        {
        }

};

int main()
{
    int x = 10;
    int y = 20;
    int z = 30;
    MyClass obj(x,y,z);

    int l = 40;
    int m = 50;
    MyClass2 obj2(x,y,z,l,m);

    return 0;
}


2022-09-22 22:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.