In: Civil Engineering
C++ constructor initializer list
Constructor initializer list:
- syntax
- when it must be used
- how to instantiate and initialize data members that are user-defined types at the same time
Constructor initializer list:
Use : Initializer List is for initializing data members in a class.
Synatx : List of members being initialized are indicated with constructor as a comma separated list being followed by a colon. Here is an example :
#include<bits/stdc++.h>
using namespace std;
class Test {
private:
int a;
int b;
public:
Test(int i = 0, int j = 0):a(i), b(j) {}
int printA() {return a;}
int printB() {return b;}
};
int main() {
Test t(10, 15);
cout<<"x = "<<t.printA()<<", ";
cout<<"y = "<<t.printB();
return 0;
}
Output of above code will be: 10 15
Must use conditions:
1. To initialize non-static constant data members.
2. To initialize reference members.
To instantiate and inititalize data that are user-defined types at the same time, that is at the time when they are being defined by the user, just see the above example of code. It is doing the same thing.