Let’s see the Sum of n number of an odd natural number using constructor and destructor in C++.
Constructor
The constructor T4Tutorials_Sum()
is a member function of the class T4Tutorials_Sum
. The constructor T4Tutorials_Sum()
has the same name as the name of its class T4Tutorials_Sum
.
- When a new object
u
of the class T4Tutorails_Series is executed, the constructorT4Tutorials_Sum()
also executed automatically. - The constructor
T4Tutorials_Sum()
has no data type. Even we can’t use void also. - The constructor
T4Tutorials_Sum()
can have arguments. - The constructor
T4Tutorials_Sum()
can be only public. - There is no inheritance of the constructor
T4Tutorials_Sum()
.
Destructor
The destructor ~T4Tutorials_Sum()
is a member function of the class T4Tutorials_Sum
. Destructor ~T4Tutorials_Sum()
has the same name as the name of its class T4Tutorials_Sum
. The tild sign ∼ is used before the name of the destructor ~T4Tutorials_Sum()
.
- When the object
obj(5)
of the classT4Tutorials_Sum
destroyed, then the destructor~T4Tutorials_Sum()
also destroyed automatically. - One class
T4Tutorials_Sum
can have only one destructor~T4Tutorials_Sum()
. However, one class can have many constructors. - Destructor
~T4Tutorials_Sum()
overloading is impossible. - The Destructor
~T4Tutorials_Sum()
can’t have any arguments(parameters). - The destructor
~T4Tutorials_Sum()
has no data type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include<iostream> using namespace std; class T4Tutorials_Sum { public : T4Tutorials_Sum(); ~T4Tutorials_Sum(); void read(); }; T4Tutorials_Sum::T4Tutorials_Sum() { cout<<endl; } void T4Tutorials_Sum::read() { { int n,s=0; cout<<"Please enter the value to print odd numbers."<<endl; cin>>n; for(int i=1;i<=n;i++) { cout<<2*i-1<<" "; s=s+(2*i-1); cout<<endl; } cout<<"T4Tutorials_Sum of given input = "<<s; } } T4Tutorials_Sum::~T4Tutorials_Sum() { cout<<endl<<"The destructor destroys everything of the constructor."; } int main() { T4Tutorials_Sum u; u.read(); } |
Output
Please enter the value to print odd numbers.
5
1
3
5
7
9
T4Tutorials_Sum of given input = 25
The destructor destroys everything of the constructor.