Const data Member

If class have const data member, then there must be a constructor with initialiser list.

Please have a look:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Test
{
public:
    Test();
    Test(int a, int b, int c);
    ~Test();
    void Print();
    void getConst() const;

private:
    int _a;
    int _b;
    const int _c;
};

Test::Test(int a, int b, int c): _c(c)
{
    cout<<"\nConstructor with one parameter\n";
    this->_a = a;
    this->_b = b;
}

is it correct?

The question is can we not write other than constructor with initialiser list?

please reply.

Last edited on

Why don't you initialise all the member variables in the initialisation list:

1
2
3
4
5
6
7
Test::Test(int a, int b, const int c)
   : _a(a),
   , _b(b)
   , _c(c)
{

}
If class have const data member, then there must be a constructor with initialiser list.
yeah that's correct but the initialiser list is to be prefered anyway so that's not really an issue for most of us.
Thanks ajh32 and Gamer2015 for reply.

@ajh32
Its just an example. We should initialise all data member(except Array type) with constructor initialiser list only, As it has its own benefits.
To answer your original question:

The question is can we not write other than constructor with initialiser list?

Only constructors can have initialiser lists. That includes copy constructors and move constructors.
Last edited on
From C++11 on you can intialize member directly:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Test
{
public:
Test();
Test(int a, int b, int c);
~Test();
void Print();
void getConst() const;

private:
int _a;
int _b;
const int _c = 42; // Note
};
Note that if you mix in-class initialization and initializer list, the 'list value overrides the in-class value.

{1, 2, 37}
{77, 180, 37}
{-3, -5, 37}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

class Test {
public:
    Test() : _a(1), _b(2) {}
    Test(int a) : _a(a), _b(180) {}
    Test(int a, int b) : _a(a), _b(b) {}
    ~Test(){}
    void Print() const;

private:
    int _a = 17;
    const int _b = 23;
    const int _c = 37;
};

void Test::Print() const {
    std::cout << "{" << _a << ", " << _b << ", " << _c << "}\n";
};

int main() {
    Test t0;
    Test t1(77);
    Test t2(-3, -5);
    t0.Print();
    t1.Print();
    t2.Print();
    return 0;
}
Last edited on
except Array type

C++11 also allows you to init array types.

{4, 5, 6}
{77, 2, 3}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

class Test {
public:
    Test() : _a{4, 5, 6} {}
    Test(int a_0) { _a[0] = a_0; }
    ~Test(){}
    void Print() const;

private:
    int _a[3] = {1, 2, 3};
};

void Test::Print() const {
    std::cout << "{" << _a[0] << ", " << _a[1] << ", " << _a[2] << "}\n";
};

int main() {
    Test t0;
    Test t1(77);
    t0.Print();
    t1.Print();
    return 0;
}
Topic archived. No new replies allowed.