Constructor Overloading C++, Sum of n number of odd natural numbers
Let’s see the C++ program to show the Sum of n number of odd natural numbers by using the Constructor Overloading.
We are using more than one constructor of the class T4Tutorials_Sum_Constructor_Overloading
with the same name, and it is called constructor overloading.
In this program, the constructor must obey one or both of the following rules.
- All constructors with the same name and having a different number of parameters.
T4Tutorials_Sum_Constructor_Overloading (int a)
and another constructor asT4Tutorials_Sum_Constructor_Overloading(int two, int three)
.
- All constructors with the same name and have the same number of parameters but of different data types.
T4Tutorials_Sum_Constructor_Overloading (int a)
and another constructor asT4Tutorials_Sum_Constructor_Overloading (double a).
Note: In this example, we are overloading the constructor with the following rule;
T4Tutorials_Sum_Constructor_Overloading(int a)
and another constructor as T4Tutorials_Sum_Constructor_Overloading(int two,int three)
.
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
#include<iostream> using namespace std; class T4Tutorials_Sum_Constructor_Overloading { private : int i,n,number1 ,number2; public : T4Tutorials_Sum_Constructor_Overloading(int a) { n=a; int sum=0; for(int i=1;i<=n;i++) { cout<<"The output is:"<<endl; cout<<2*i-1<<" "; sum=sum+(2*i-1); cout<<endl; } cout<<"The sum of the given input = "<<sum<<endl; } T4Tutorials_Sum_Constructor_Overloading(int two,int three) { cout<<"For 1st Input Answer is Given below"<<endl; number1 =two; int sum1=0; for(int i=1;i<=number1 ;i++) { cout<<"The output is:"; cout<<2*i-1<<" "; sum1=sum1+(2*i-1); cout<<endl; } cout<<"The sum of the given input = "<<sum1<<endl; cout<<endl; cout<<"For 2nd Input Answer is Given below."<<endl; number2=three; int sum2=
0; for(int i=1;i<=number2;i++) { cout<<"The output is:"; cout<<2*i-1<<" "; sum2=sum2+(2*i-1); cout<<endl; } cout<<"The sum of the given input = "<<sum2<<endl; } }; int main() { int option; cout<<"Enter 1 of Single parameter constructor."<<endl; cout<<"Enter 2 For Multiple Paramter constucor."<<endl; cout<<"Input 1 or 2 here : "<<endl; cin>>option; system("cls"); if(option ==1) { cout<<"You Have Slected Single Paramater"<<endl; cout<<"Constructor"<<endl; int n; cout<<"enter the value : To print Odd Number"<<endl; cin>>n; T4Tutorials_Sum_Constructor_Overloading a(n); } else if(option==2) { cout<<"You Have slected Multiple Paramater"<<endl; cout<<"Constructor"<<endl; int two,three; cout<<"enter the 1st value : To print Odd Number"<<endl; cin>>two; cout<<"enter the 2nd value : To print Odd Number"<<endl; cin>>three; T4Tutorials_Sum_Constructor_Overloading(two,three); } else cout<<"Wrong Input "; } |
Output