Advertisements

Archive

Posts Tagged ‘Cpp Constructors’

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


Advertisements

C++ Program to implement Constructor Overloading – Q13

January 13, 2010 Leave a comment

Q13. Program to implement Constructor Overloading:

Implement the concept of Constructor Overloading with the help of not less than three different constructors within any class of your choice.

… from College notes (BCA/MCA assignments):

#include <iostream.h>
#include <conio.h>
#include <string.h>

class Cperson{
	private:
		char name[20];
	public:
		Cperson(){
			cout<<"\n Constructor Called."<<endl;
			strcpy(name, "Manoj");
			}
		Cperson(char *str){
			strcpy(name, str);
			}
		Cperson(Cperson &per){
			strcpy(name, per.name);
			}
		void Show_Name(){
			cout<<name;
			}
	};

void main(){
	clrscr();

	Cperson Op1;
	Cperson Op2("Pandey");
	Cperson Op3(Op2);

	cout<<"\n Op1: ";
	Op1.Show_Name();

	cout<<"\n Op2: ";
	Op2.Show_Name();

	cout<<"\n Op3: ";
	Op3.Show_Name();

	getch();
	}

 

Output:

Constructor Called.

Op1: Manoj
Op2: Pandey
Op3: Pandey