How do you initialize a class member,
class x {
const int i;
};

Answer Posted / jp

const data members must be initialized using Initializer List. In the following example, “t” is a const data member of Test class and is initialized using Initializer List.

#include<iostream>
using namespace std;

class Test {
const int t;
public:
Test(int t):t(t) {} //Initializer list must be used
int getT() { return t; }
};

int main() {
Test t1(10);
cout<<t1.getT();
return 0;
}

/* OUTPUT:
10
*/

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Explain how a pointer to function can be declared in C++?

796


Explain the virtual inheritance in c++.

826


What does 7/9*9 equal ? a) 1 b) 0.08642 c) 0

769


What do you mean by vtable and vptr in c++?

835


Is it possible for the objects to read and write themselves?

893


What do you mean by persistent and non persistent objects?

1113


What is buffer and example?

739


What is difference between array and vector in c++?

778


What is binary search in c++?

815


How to demonstrate the use of a variable?

870


the maximum length of a character constant can be a) 2 b) 1 c) 8

914


What are single and multiple inheritances in c++?

794


What is oops in c++?

815


Can we use pointers in c++?

827


Explain what are single and multiple inheritances in c++?

761