Anda di halaman 1dari 12

Session Objectives

Explain Copy Constructor


Conversion Constructor Explain Destructor Rules for Framing a Destructor

This constructor function designed to copy objects of

the same class type.


It accepts a single argument and returns a copy of an object

It can also be called if you initialize a new object with another object of same type
Arguments cannot be passed by value provide way to create a object by making a copy of an existing object

#include <iostream.h> #include <string.h> #include <conio.h> class item { private : int itno; char itname[20]; float price; public : item(int a,char *b,float c) { itno=a;

strcpy(itname,b); price=c; } item(item &ptr) { itno=ptr.itno; strcpy(itname,ptr.itname); price=ptr.price; } void showitem() { cout<<itno<<itname<<price; }};

void main() { clrscr(); item i1(1,"Monitor",3800),i2(i1); cout<<"First item"<<endl; i1.showitem(); cout<<"Second item"<<endl; i2.showitem(); getch(); }
First item 1 Monitor 3800 Second item 1 Monitor 3800

Destructor is a special member function that is called automatically when an object is destroyed that have been created by constructor
It can be used to deallocate the memory space

Need for destructor


The programmer is relived of the task of clearing the memory space occupied by the data members every time an object goes out of scope.

RULES
It should be declared inside public It has no return types It has no argument or parameters Prefixed by tilde(~) symbol So a program can have only one destructor

Syntax
~Classname( ) { Statements; }

Has to be destroyed

object

complier
calls

Destructor De-allocates

memory

Example for destructor


#include<iostream.h> #include<conio.h> class exam { private: int sno,mark1,mark2; public: exam( ) //constructor { sno=mark1=mark2=100; } void showdata() { cout<<sno<<mark1<<mark2 } ~exam() //Destructor { cout<<"destructo is invoked"; }};

void main(){ exam e; e.showdata(); exam e1(1,90,90); clrscr(); e1.showdata(); getch(); } }

Sno = 100 Mark1 = 100 Mark2 =100 Sno = 100 Mark1 = 100 Mark2 =100 destructor is invoked

#include<iostream.h> #include<conio.h> void main() { int fact,n; int factorial(int); clrscr(); cout<<"Enter Your Number "<<endl; cin>>n; fact=factorial(n); cout<<endl<<"The Factorial Value is " <<fact; getch(); }

int factorial(int x) { if(x==1) return 1; else return x*factorial(x-1); }

A constructor is a special member function which is executed automatically when an object is created A Destructor is a special member function which is executed automatically when an object is destroyed

EXERCISES
1. 2. 3. 4. 5. Explain the use of constructors in a class? Explain the use of Destructors in a class? State the difference between Constructors & Destructors? Explain Default constructor with Example? Explain the use of Copy constructor in a class?

Anda mungkin juga menyukai