C++ - Initialization of Array of Objects with Parameterized Constructor in C++ program.


IncludeHelp 03 September 2016

In this code snippet we will learn how we can initialize array of objects with parameterized constructor in c++ programming language?

In this example there is class named Number and through parameterized constructor we are assigning an integer value to the private member of class.

In this example array of objects will be declared and initialized through parameterized constructor. We will declare array of objects by two types 1) Static Declaration and 2) Dynamic Declaration through Pointer. Both will be initialized through parameterized constructor.

C++ Code Snippet - Initialization of Array of Objects with Parameterized Constructor in C++ program

#include <iostream>
using namespace std;

class Number{
	private:
		int num;
	public:
		//default constructor
		Number(){num=0;}
		//parameterized constructor
		Number(int n){
			num=n;
		}
		//display number
		void dispNumber(){
			cout<<"Num is: "<<num<<endl;
		}		
};

int main(){
	//declaration array of objects 
	//with parameterized constructor
	Number N[3]={Number(10),Number(20),Number(30)};
	
	N[0].dispNumber();
	N[1].dispNumber();
	N[2].dispNumber();
	
	return 0;		
}
    Num is: 10
    Num is: 20
    Num is: 30

Array of objects Initialization using Pointers/ Dynamic Initialization

int main(){
	//declaration array of objects 
	//with parameterized constructor
	Number *N;
	
	N=new Number[3]{{10},{20},{30}};
	
	N[0].dispNumber();
	N[1].dispNumber();
	N[2].dispNumber();
	
	return 0;		
}






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.