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
Which is the best c++ compiler?
What are punctuators in c++?
Explain how overloading takes place in c++?
What are the advantages of using friend classes?
What is c++ library?
What are the various compound assignment operators in c++?
Describe exception handling concept with an example?
Why do we use classes in programming?
What is the difference between method overloading and method overriding in c++?
Is c++ a float?
Arrange Doubly linked list in the ascending order of its integral value and replace integer 5 with 7?
Differentiate between the manipulator and setf( ) function?
What are manipulators used for?
Difference between declaration and definition of a variable.
What is lvalue?