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.






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.