Constructors/Destructors Functions Revisited Powerpoint 7 Constructors/Destructors Functions Revisited
Constructors C++ Has no return value May have parameters Called automatically when a class object is declared C++ has default constructors that are called whenever a class is declared even if no function with the same name exists Should be public (or protected)
C++ Does not have a return type Cannot have parameters Called automatically when the class object is destroyed Deactivates storage allocated to a class Declared with a tilde (~)
Example of Constructor class sum { public: sum(); private: int sum1,sum2; };
C++ void main () { sum obj1; //constructor is called at this //time cout<<“end of main”<<endl; return; }
C++ Functions sum::sum () { sum1=0; sum2=10; cout<<sum1<<“ “<<sum2<<endl; }
C++ Sample Functions What is the output??
the answer 0 10 end of main
Example of Constructor withArguments class sum { public: sum(int,int); private: int sum1,sum2; };
C++ void main () { sum obj1 (10,20); //constructor is // called at this time cout<<“end of main”<<endl; return; }
C++ Functions sum::sum (int x,int y)) { sum1=x; sum2=y; cout<<sum1<<“ sum1”; cout<<sum2<<“ sum2”<<endl; }
C++ Sample Functions What is the output?? 10 sum1 20 sum2 end main
Destructor: Also a function Identified by a ~ preceding function name Called automatically when a class object is destroyed May not have arguments Should be public (or protected)
public: ~sum (); sum::~sum ( ) { close (infile); close (outfile); }