Professional Documents
Culture Documents
• a is an integer array.
class array • It is declared as a private data
{ int a[10]; member of the class array.
public: • Can be used in class member
void setVal(); functions.
void sort();
void display();
};
2
Example
1. #include<iostream>
2. using namespace std;
3. class array
4. { int a[10];
5. public:
6. void setVal()
7. { for (int i = 0; i < 10; i++) cin >> a[i]; }
8. void sort()
9. { for (int i = 0; i < 9; i++)
10. for (int j = 0; j < 10 - i - 1; j++)
11. { if (a[j] > a[j + 1])
12. { a[j] = a[j] + a[j + 1];
13. a[j + 1] = a[j] - a[j + 1];
14. a[j] = a[j] - a[j + 1]; } }
15. } 3
Contd…
16. void display()
17. { for (int i = 0; i < 10; i++) cout << a[i] << '\t';
18. }
19. };
20. int main()
21. { array Arr;
22. Arr.setVal();
23. Arr.sort();
24. cout << "Sorted sequence is:\n";
25. Arr.display();
26. }
Output:
10 9 8 7 6 5 4 3 2 1
Sorted sequence is:
1 2 3 4 5 6 7 8 9 4
10
Memory allocation for objects of class
5
Contd…
• During class specification
– No memory space is allocated for the class data
members.
– Memory is allocated to class member functions once
they are defined as a part of class specification.
• During object creation
– No separate space is allocated for class member
functions, they remain same for all objects.
– Memory is allocated for class data members
separately for each object as they hold different data
values for different objects.
6
Array of objects
• It is possible to have arrays of objects.
– Means array of variables of type class.
• The syntax for declaring and using an object array is
exactly the same as it is for any other type of array.
– Use usual array-accessing methods to access
individual elements, and then the dot member
operator to access the member functions.
• An array of objects is stored inside the memory in
the same way as a multi-dimensional array.
7
Contd…
8
Contd…
• An array of objects is stored similar to multi-
dimensional array.
emp manager[3];
name
manager[0]
age
name
manager[1]
age
name
manager[2]
age
9
Example
1. #include<iostream>
2. using namespace std;
3. class emp
4. { char name[10];
5. int age;
6. public:
7. void getData();
8. void putData();
9. };
10. void emp :: getData()
11. { cout << "Enter Name: "; cin >> name;
12. cout << "Enter Age: "; cin >> age; }
13. void emp :: putData()
14. { cout << "\tName: " << name << "\tAge: " << age << endl; }
10
Contd…
15. int main()
16. { emp manager[3];
17. for (int i = 0; i < 3; i++)
18. { cout << "\nEnter details of manager " << i + 1 << endl;
19. manager[i].getData();
20. }
21. for (int i = 0; i < 3; i++)
22. { cout << "\nManager " << i + 1;
23. manager[i].putData();
24. }
25. return 0;
26. }
11
Contd…
Enter details of manager 1
Enter Name: Arun
Enter Age: 50
18