C++ Array of Objects with Example in OOP

C++ Array of Objects in OOP | Array of Objects with Example in C++| OOP Tutorial in C++

In this tutorial, we are going to learn about the C++  Array of Objects in OOP,  Array of Objects with Example in C++,OOP Tutorial in C++

What is Array of Objects in C++?

An object of class represents a single record in memory, if we want more than one record of class type, we have to create an array of class or object.

Creating more than one object of similar type is called Array of objects in C++ by creating an array of type class.

Syntax:

class-name array-name[size];  

Remember: An array objects are always stored in consecutive memory locations, be it an array containing primitive values or object references.

 

Like array of other user-defined data types, an array of type class can also be created.

The array of type class contains the objects of the class as its individual elements.

Thus, an array of a class type is also known as an array of objects.

An array of objects is declared in the same way as an array of any built-in data type.

 

Let's see an example of taking the input of name and marks of 5 students by creating an array of the objects of students.

Array of Objects Example :

 #include <iostream>

#include <string>

using namespace std;

class Student{

string name;

int marks;

public:

void getName()

{

getline( cin, name );

}

void getMarks()

{

cin >> marks;

}

void displayInfo()

{

cout << "Name : " << name << endl;

cout << "Marks : " << marks << endl;

}};

int main(){

Student st[5];

for( int i=0; i<5; i++ )

{

cout << "Student " << i + 1 << endl;

cout << "Enter name" << endl;

st[i].getName();

cout << "Enter marks" << endl;

st[i].getMarks();

}

for( int i=0; i<5; i++ )

{

cout << "Student " << i + 1 << endl;

st[i].displayInfo();

}

return 0;

}


Output

Student 1
Enter name
Jack
Enter marks
54
Student 2
Enter name
Marx
Enter marks
45
Student 3
Enter name
Julie
Enter marks
47
Student 4
Enter name
Peter
Enter marks
23
Student 5
Enter name
Donald
Enter marks
87
Student 1
Name : Jack
Marks : 54
Student 2
Name : Marx
Marks : 45
Student 3
Name : Julie
Marks : 47
Student 4
Name : Peter
Marks : 23
Student 5
Name : Donald
Marks : 87

Student st[5]; - We created an array of 5 objects of the Student class where each object represents a student having a name and marks.
The first for loop is for taking the input of name and marks of the students. getName() and getMarks() are the functions to take the input of name and marks respectively.
The second for loop is to print the name and marks of all the 5 students. For that, we called the displayInfo() function for each student.


Previous Post: C++ Destructors in OOP | Rules & Properties of Destructor in OOP


Next Post: C++ Object Pointers in OOP | C++ Object Reference in OOP | Difference Between Reference and Pointer |OOP Tutorial in C++


0 Response to C++ Array of Objects with Example in OOP

Post a Comment