Archive
Posts Tagged ‘Dynamic Class’
C++ Program to implement Dynamic Class with Constructor & Destructor – Q15
January 15, 2010
Leave a comment
Q15. Program to implement Dynamic Class with Constructor & Destructor:
Get the sum of elements of an array with user defined size, used dynamically within class using new & delete inside class constructor & destructor respectively.
… from College notes (BCA/MCA assignments):
#include <iostream.h> #include <conio.h> #include <string.h> class CArray{ private: int *arr; int len, sum; public: CArray(){ sum = 0; } CArray(int s){ len = s; arr = new(int[len]); } ~CArray(){ delete(arr); } void getArray(); void Sum(); void Display(); }; void CArray :: getArray(){ cout<<"\n Enter "<<len<<" elements in an Array: "; for(int i=0;i <len; i++) cin>>arr[i]; } void CArray :: Sum(){ for(int i=0; i<len; i++) sum += arr[i]; } void CArray :: Display(){ cout<<"\n Total Sum: "<<sum; } void main(){ int sz; clrscr(); cout<<"\n Enter the Size of Array: "; cin>>sz; CArray Oarr(sz); Oarr.getArray(); Oarr.Sum(); Oarr.Display(); getch(); }
Output:
Enter the Size of Array: 5
Enter 5 elements in an Array: 33 21 45 76 39
Total Sum: 214
Categories: Cpp
Cpp, Cpp Constructors, Cpp Destructors, Dynamic Class