Q:

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

belongs to collection: C++ programs on various topics

0

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

 

 

 

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ - program for Nested Structure (Structure with... >>
<< C++ program to declare an integer variable dynamic...