Creation of Array of Objects in C++

0
480

Hey guys, Another C++ Programming Tutorial for Beginners. In this article, you will learn the Creation of Array of Objects in C++. We will see this new concept by using an example program below. There are two methods of creating the array of objects:

 Creation of Array of Objects in C++
 Creation of Array of Objects in C++

1st method to Create Array of Objects in C++ : dynamically=>

#include<iostream.h>
#include<conio.h>
class student
{
int age;
char name[10];
public:
void display()
{
cout<<“\n the name is:\n”<<name;
cout<<“\t the age is:\n”<<age;
}
void read()
{
cout<<“enter name and age:”;
cin>>name>>age;
}
};
void main()
{
int n;
clrscr();
student ob;
cout<<“enter the size of the array:”;
cin>>n;
for(int i=0;i<n;i++)
{
ob.read();
ob.display();
}
student *p=new student[n]; //array created                                                        dynamically
getch();
}

In this program we have created a class named ‘student’ and declared variables ‘name’ and ‘age’ and also declared the member functions, ‘read()’ to take the input and ‘display()’ to show the output. Now in the main(), we have created a dynamic array of objects, so at now we can take ‘n’ number of inputs according to the user and show it to the user.

Syntax: class_name * pointer_variable=new class_name [size];

By using the dynamic array of objects we can declare and use the objects according to the user.

Learn More: C++ Programs for Beginners

2nd method for creation of array of objects in c++: by initialization in main=>

 

#include<iostream.h>
#include<conio.h>

class student
{
int age;
char name[10];
public:
void display()
{
cout<<“the name is: \n”<<name;
cout<<“\t the age is: \n”<<age;
}
void read()
{
cout<<“enter the name and age:”;
cin>>name>>age;
}
};
void main()
{
clrscr();
student ob[5];
for(int i=0;i<5; i++)
{
ob[i].read();
ob[i].display();
cout<<“\n”;
}
getch();
}

This program is almost same as the above program but a little difference in the main. Instead of dynamic array of objects, we fixed the size to 5 that means, we have created 5 objects named ‘ob’ and each ‘ob’ is taking input from the user and giving output according to the value entered by the user. We have used ‘for’ loop in the main to take input and show output to the user. The ‘for’ loop will repeatedly take input and show output until it’s value exceeds 5.

If you liked this article, do give us +1 on Google Plus of share this article on Facebook. Help us to reach more and share quality articles with your friends. Hope you’re clear on the concept of an array of objects in C++ Programming. If you have any doubts regarding this, do let us know by commenting below.

LEAVE A REPLY

Please enter your comment!
Please enter your name here