Constructors parameter name is same as data member using Member Initializer List in C++ Programming


The program demonstrates the use of constructor initialization lists in C++ classes.

The student class has two private data members: name and age. It has a parameterized constructor that takes in name and age as parameters. Instead of using the traditional constructor implementation (commented out in the code), the constructor is implemented using an initialization list :name(name), age(age) . This means that when an object is created, the values of name and age are directly initialized with the values passed to the constructor. This method is more efficient and faster than initializing the values in the body of the constructor.

The print() function is used to print the values of name and age for the object created in the main() function. The student object o is created with the values "Ram Kumar" for name and 25 for age. The print() function is called to display these values.

Source Code

// Constructor’s parameter name is same as data member
#include<iostream>
using namespace std;
class student
{
private:
    string name;
    int age;
public:
    /*student(string name,int age)
    {
        this->name=name;
        this->age=age;
    }*/
    student(string name,int age):name(name),age(age){}
    void print()
    {
        cout<<"Name : "<<name<<endl;
        cout<<"Age  : "<<age<<endl;
    }
};
 
int main()
{
    student o("Ram Kumar",25);
    o.print();
    return 0;
}
 

Output

Name : Ram Kumar
Age  : 25
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples