C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C++ programming language

Array of objects initialization with constructors in C++

Here, we will learn how to initialize array of objects using constructors in C++?

In this program, we will define a class and declare array of objects, declare object (array of objects) will be initialized through the constructor.

Here, we are going to define a class named person with two members name and age. These members will be initialized through constructors (default and parameterized).

Program to initialize array of objects in C++ using constructors

#include <iostream>
#include <string.h>
using namespace std;

class person
{
	private:
		char name[50];
		int age;
	public:
		//default constructor
		person()
		{
			strcpy(name,"N/A");
			age=0;
		}
		
		//parameterized constructor with default argument
		person(char *name, int age=18)
		{
			strcpy(this->name,name);
			this->age=age;
		}
		
		//function to display values
		void display()
		{
			cout<<name<<"\t"<<age<<endl;
		}		
};

int main()
{
	//array of class objects declaration
	person per[4]={"ABC",person("PQR"),person("XYZ",30)};
	
	per[0].display();
	per[1].display();
	per[2].display();
	per[3].display();
	
	return 0;
}

Output

ABC		18
PQR		18
XYZ		30
N/A		0

In the statement person per[4]={"ABC",person("PQR"),person("XYZ",30)};, there are 4 objects and only three initializer values "ABC" - Here, parameterized constructur will call, "ABC" will be assigned into name and age will be default value that is 18.

person("PQR") - Here, parameterized constructur will call, "PQR" will be assigned into name and age will be default value that is 18.

person("XYZ",30) - Here, parameterized constructur will call, "XYZ" will be assigned into name 30 will be assigned into age.

DEFAULT Constructor - Last object p[3] wil be initialized using default constructor, the values of name will be "N/A" and age will be 0.







COMMENTS