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.
// 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; }
Name : Ram Kumar Age : 25To download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions