Advertisements
Home > Cpp > C++ Program to implement Dynamic Class with Constructor & Destructor – Q15

C++ Program to implement Dynamic Class with Constructor & Destructor – Q15


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


Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: