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;		
}



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.