Home » C++ programming language

Initialization of Array of Objects in C++

We can initialize array of objects with the help of constructors, especially parameterized constructor. Parameterized constructor passes the given value (while declaration of the object) to the variables associated to the object.

Let's consider the following example/program

#include <iostream>
using namespace std;

class Number
{
	private:
		int a;
		float b;
	public:
		//defaultconstructor
		Number(){a=0;b=0.0f;}
		//Parameterized constructor
		Number(int x,float y)
		{
			a=x;
			b=y;
		}
		//print function
		void printValue()
		{
			cout<<"a="<<a<<",b="<<b<<endl;
		}
};

int main()
{
	Number NUM[3]=
			{
				Number(10,20.00f),
				Number(15,30.56f),
				Number(20,45.50f)
			};
	NUM[0].printValue();
	NUM[1].printValue();
	NUM[2].printValue();
	
	return 0;
}
    a=10,b=20 
    a=15,b=30.56
    a=20,b=45.5

In this program, Number is a class and NUM is the array of objects.

While creating the array of objects, we are passing the constructor with values as array arguments and the variables a, b will be initialized with the corresponding values.







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.