Dynamic Initialization of Objects in C++

C++ | Dynamic Initialization of Objects: Here, we will learn how to initialize the object at run time i.e. Dynamic Initialization?
Submitted by IncludeHelp, on September 20, 2018 [Last updated : March 02, 2023]

C++ Dynamic Initialization of Objects

The Dynamic Initialization of Objects means to initialize the data members of the class while creating the object. When we want to provide initial or default values to the data members while creating of object - we need to use dynamic initialization of objects.

Now, the question is how to achieve or implement dynamic initialization of objects?

It can be implemented by using parameterized constructors in C++.

Example:

Here, we have a class named "Student" which contains two private data members 1) rNo - to store roll number and 2) perc - to store percentage.

C++ program to implement dynamic initialization of objects

#include <iostream>
using namespace std;

//structure definition with private and public members
struct Student {
private:
    int rNo;
    float perc;

public:
    //constructor
    Student(int r, float p)
    {
        rNo = r;
        perc = p;
    }

    //function to read details
    void read(void)
    {
        cout << "Enter roll number: ";
        cin >> rNo;
        cout << "Enter percentage: ";
        cin >> perc;
    }
    //function to print details
    void print(void)
    {
        cout << endl;
        cout << "Roll number: " << rNo << endl;
        cout << "Percentage: " << perc << "%" << endl;
    }
};

//Main code
int main()
{
    //reading roll number and percentage to initialize
    //the members while creating object
    cout << "Enter roll number to initialize the object: ";
    int roll_number;
    cin >> roll_number;
    cout << "Enter percentage to initialize the object: ";
    float percentage;
    cin >> percentage;

    //declaring and initialize the object
    struct Student std(roll_number, percentage);
    //print the value
    cout << "After initializing the object, the values are..." << endl;
    std.print();

    //reading and printing student details
    //by calling public member functions of the structure
    std.read();
    std.print();

    return 0;
}

Output

Enter roll number to initialize the object: 101
Enter percentage to initialize the object: 84.02
After initializing the object, the values are...

Roll number: 101
Percentage: 84.02%
Enter roll number: 102
Enter percentage: 87

Roll number: 102
Percentage: 87%





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.