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
What are pointer-to-members? Explain.
How to declare a function pointer?
What is pure virtual function?
What is iterator in c++?
What is vector pair in c++?
What is the purpose of extern storage specifier?
Does c++ have foreach?
What do you mean by function pointer?
What is command line arguments in C++? What are its uses? Where we have to use this?
If I is an integer variable, which is faster ++i or i++?
What relational operators if statements in c++?
What is the protected keyword used for?
Can turbo c++ run c program?
Can a program run without main function?
What is implicit conversion/coercion in c++?