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


Please Help Members By Posting Answers For Below Questions

What is binary object model?

600


what is Member Functions in Classes?

617


How does class accomplish data hiding in c++?

660


How can you tell what shell you are running on unix system?

639


Can constructor be private in c++?

604






What are the various situations where a copy constructor is invoked?

606


How can I improve my c++ skills?

556


What happens if a pointer is deleted twice?

787


How does atoi function work?

624


what is Loop function? What are different types of Loops?

639


What do you mean by const correctness?

627


Write a program to find the Factorial of a number

570


What is an operator function? Describe the function of an operator function?

612


Which operator cannot overload?

541


Give an example of run-time polymorphism/virtual functions.

561