Arrays as Class Data Member
Submitted by moazkhan on Tuesday, July 29, 2014 - 22:37.
Arrays as Class Data Member
In this tutorial you will learn: 1. How to make Arrays as Class Data Member? 2. Why to use arrays as attributes of the class? 3. How to make array of objects? 4. C++ syntax Arrays can also be the data members of the class, just like integer, float and other data type integers we can also define an array as the data members. Arrays are used as data members because if the user requires that the object contain a lot of information which is to be saved in the array then he will use array as the data member of the class. It must be noted here that whenever we define array as the data member of the class we must define its size dynamically and if we don’t do so then the we have to define the array dynamically using ‘new’ keyword. Arrays as the data member of the class can be defined as follow Class myclass { private: int a[5]; // here we write remaining part of the class }; We can also make array of objects, but this is done in main of the program. It allows us to make a lot of objects and store them in an array. By making an array of objects we can set the values of all the objects using the smaller piece of code. We define an array of objects and initialzed the value using ‘setDist’ function in the main as follow void main() { Distance dist[100]; for (int i=0; i100; i++) dist[i].setDist(); } In the code below we have made stack using the Array data member. It also has the two functions which are necessary for a stack, Push and Pop. Push function pushes in the integer at the top of stack while the pop function remove the integer from the top of the stack. strong>Array as Data Member Basic Step: Open Dev C++ then File > new > source file and start writing the code below.- #include<iostream>
- #include<conio.h>
- using namespace std;
- const int MAX=10;
- class Stack {
- int st[MAX];
- int top;
- public:
- Stack() : top(-1) {}
- void push(int var) {st[++top]=var;}
- int pop() {return st[top--];}
- };
- void main()
- {
- Stack s1;
- int a,b;
- cout<<"Please Enter the First number you want to push in Array Data Member:";
- cin>>a;
- s1.push(a);
- cout<<"\nPlease Enter the Second number you want to push in Array Data Member:";
- cin>>b;
- s1.push(b);
- cout<<"---------------------Popping out integers from Array------------------------\n";
- cout<<"\nAfter popping out first integer from Array:"<<s1.pop()<<endl;
- cout<<"\nAfter popping out second integer from Array:"<<s1.pop()<<endl;
- }
Add new comment
- 624 views