What is a constructor initializer list and when we use
constructor initializer list?
Answer Posted / sachin mahajan
Main purpose of the contstuctor is to initialize the data
members with some valid values. This can be done in two ways
class MyClass{
int I,J;
public:
MyClass(int i,int j )
{
I=i;J=j;
}
};
Above the most common way to initialize data members .Other
way is
MyClass(int i,int j):I(i),J(j)
{
}
i(0),j(0) is the initialization list.
Constuctor Initialization list is used when we want to pass
some data to the constructor the parent class.
Below is the example:
class Parent
{
int I;
public:
Parent(int i)
{
I=i;
}
};
class Child:public Parent
{
int J;
public:
Child(int i,int j):Parent(i),J(j)
{
}
};
main()
{
Child c(1,2);
//now 1 is passed to parent and 2 is passed to Child
}
| Is This Answer Correct ? | 12 Yes | 5 No |
Post New Answer View All Answers
What information can an exception contain?
What is low level language in simple words?
How does class accomplish data hiding in c++?
What is flag in computer?
Show the application of a dynamic array with the help of an example.
What sorting algorithm does c++ use?
How would you use the functions memcpy(), memset(), memmove()?
What do you mean by storage classes?
What is c++ flowchart?
Is c++ a good beginners programming language?
What are the two types of comments?
Inline parameters : What does the compiler do with the parameters of inline function, that can be evaluated in runtime ?
Is vector a class in c++?
Explain deep copy?
What do nonglobal variables default to a) auto b) register c) static