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
How to declare a function pointer?
Why is c++ difficult?
Why c++ does not have finally?
Difference between a homogeneous and a heterogeneous container
Is c++ a software?
What is an iterator class in c++?
What does the linker do?
What does it mean to declare a member function as virtual?
Differentiate between declaration and definition.
What is abstract keyword in c++?
When do we use copy constructors?
What is the function to call to turn an ascii string into a long?
What is abstract class in c++?
Why ctype h is used in c++?
How do I run c++?