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
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
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(); }
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?