Home » C++ programs » C++ constructor and destructor programs

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

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++.


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.


#include <iostream>
using namespace std;

//structure definition with private and public memebers
struct Student
		int rNo;
		float perc;

			Student(int r, float p)
				rNo = r;
				perc = p;

			//function to read details
			void read(void)
				cout<<"Enter roll number: ";
				cout<<"Enter percentage: ";
			//function to print details
			void print(void)
				cout<<"Roll number: "<<rNo<<endl;
				cout<<"Pecentage: "<<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;
	cout<<"Enter percentage to initialize the object: ";
	float percentage;

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

	//reading and printing student details 
	//by calling public member functions of the structure

	return 0;


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
Pecentage: 84.02%
Enter roll number: 102
Enter percentage: 87.95

Roll number: 102
Pecentage: 87.95%

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.