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

What do you mean by “this” pointer?

613


Is set c++?

565


What is the difference between a type-specific template friend class and a general template friend class?

551


Explain explicit container.

631


What are static member functions?

613






How much maximum can you allocate in a single call to malloc()?

629


What is functions syntax in c++?

613


What is stack unwinding?

603


How do you print a string on the printer?

571


How a pointer differs from a reference?

689


What is function prototyping? What are its advantages?

586


What is the hardest coding language to learn?

596


Assume studentNames and studentIDs are two parallel arrays of size N that hold student data. Write a pseudocode algorithm that sorts studentIDs array in ascending ID number order such that the two arrays remain parallel.

1711


What is double in c++?

557


What are the two types of comments?

570