C++ Program to display the cube of the number upto a given integer using constructor overloading
Write C++ Program to display the cube of the number upto a given integer using constructor overloading.
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()
and another constructor asT4Tutorials(int p, int q)
.
- All constructors with the same name and have the same number of parameters but of different data types.
T4Tutorials(int p, int q)
and another constructor asT4Tutorials(double p, double q)
.
Note: In this example, we are overloading the constructor with the following rule;
One constructor as T4Tutorials()
and another constructor as T4Tutorials(int p, int q)
.
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 |
#include<iostream> #include<conio.h> using namespace std; class T4Tutorials { private: int i,n; public: T4Tutorials() { i=1; n=0; } T4Tutorials(int p, int q) { i=p; n=q; } void display() { cout<<"Please enter the number:"<<endl; cin>>n; for(i=1; i<=n; i++) { cout<<" cube of"<<i<<"is:"<<(i*i*i)<<endl; } } }; int main() { int p,q; T4Tutorials object(p,q); T4Tutorials object2; object.display(); getch(); } |
Output
Please enter the number:
3
cube of 1 is: 1
cube of 2 is: 8
cube of 3 is: 27