Presentation is loading. Please wait.

Presentation is loading. Please wait.

Constructors/Destructors Functions Revisited

Similar presentations


Presentation on theme: "Constructors/Destructors Functions Revisited"— Presentation transcript:

1 Constructors/Destructors Functions Revisited
Powerpoint 7 Constructors/Destructors Functions Revisited

2 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)

3 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 (~)

4 Example of Constructor
class sum { public: sum(); private: int sum1,sum2; };

5 C++ void main () { sum obj1; //constructor is called at this //time
cout<<“end of main”<<endl; return; }

6 C++ Functions sum::sum () { sum1=0; sum2=10;
cout<<sum1<<“ “<<sum2<<endl; }

7 C++ Sample Functions What is the output??

8 the answer 0 10 end of main

9 Example of Constructor withArguments
class sum { public: sum(int,int); private: int sum1,sum2; };

10 C++ void main () { sum obj1 (10,20); //constructor is
// called at this time cout<<“end of main”<<endl; return; }

11 C++ Functions sum::sum (int x,int y)) { sum1=x; sum2=y;
cout<<sum1<<“ sum1”; cout<<sum2<<“ sum2”<<endl; }

12 C++ Sample Functions What is the output?? 10 sum1 20 sum2 end main

13 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)

14 public: ~sum (); sum::~sum ( ) { close (infile); close (outfile); }


Download ppt "Constructors/Destructors Functions Revisited"

Similar presentations


Ads by Google