Sum of the series Using Constructor Overloading in C++
Sum of the series Using Constructor Overloading in C++.
The concept of using more than one constructor with the same name 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_Constructor_Overloading(int n)
and another constructor asT4Tutorials_Constructor_Overloading(int num1,int num2)
.
- All constructors with the same name and have the same number of parameters but of different data types.
T4Tutorials_Constructor_Overloading(int n)
and another constructor asT4Tutorials_Constructor_Overloading(double n)
.
Note: In this example, we are overloading the constructor with the following rule;
T4Tutorials_Constructor_Overloading(int n)
and another constructor as T4Tutorials_Constructor_Overloading(int num1,int num2)
.
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 |
#include<iostream> using namespace std; class T4Tutorials_Constructor_Overloading { protected : int i,k; int n,sum; int num1, sum1; int num2, sum2; public : T4Tutorials_Constructor_Overloading(int n) { i=1;k=9,sum=0; for(int i=1;i<=n;i++) { sum=sum+k; k=k*10+9; } cout<<"sum of series"<<sum; } T4Tutorials_Constructor_Overloading(int num1,int num2) { i=1;k=9,sum1=0; for(int i=1;i<=num1;i++) { sum1=sum1+k; k=k*10+9; } cout<<"sum os series"<<sum1<<endl; i=1;k=9,sum2=0;
for(int i=1;i<=num2;i++) { sum2=sum2+k; k=k*10+9; } cout<<"sum os series"<<sum2<<endl; } }; int main() { int option; cout<<"Please Enter 1 FOR Single parameter T4Tutorials_Constructor_Overloadingor "<<endl; cout<<"Please Enter 2 FOR Multiple Paramter construcor "<<endl; cin>>option; if(option ==1) { cout<<"You Have Slected Single Paramater T4Tutorials_Constructor_Overloadingor "<<endl<<endl; int n; cout<<"Please Enter a Number to find series : "<<endl; cin>>n; T4Tutorials_Constructor_Overloading a(n); } else if(option==2) { cout<<"*** You Have slected Multiple Paramater T4Tutorials_Constructor_Overloadingor ***"<<endl<<endl; int num1,num2; cout<<" Please Enter 1st Number to find series : "; cin>>num1; cout<<" Please Enter 2nd Number to find series : "; cin>>num2; T4Tutorials_Constructor_Overloading a(num1, num2); } else cout<<"invalid Input "; } |
Output
Please Enter 1 FOR Single parameter constructor.
Please Enter 2 FOR Multiple Paramter construcor.
1
You Have Selected Single Parameter constructor.
Please Enter a Number to find series :
5
111105