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

How do I tokenize a string in c++?

818


Does std endl flush?

794


Define pure virtual function?

751


Why is it necessary to use a reference in the argument to the copy constructor?

861


Differentiate between the manipulator and setf( ) function?

840


Define a conversion constructor?

828


What is doubly linked list in c++?

841


What operator is used to access a struct through a pointer a) >> b) -> c) *

860


What is the default access level?

828


What is abstraction in c++ with example?

793


What does it mean to declare a member variable as static?

819


Is c++ fully object oriented?

734


If dog is a friend of boy, is boy a friend of dog?

780


What are guid? Why does com need guids?

799


Evaluate the following expression as C++ would do :8 * 9 + 2 * 5 a) 82 b) 79 c) 370 d) list

809