Constructor in C++: Constructor will be the same as class name in CPP programming language. In previous page, we have discussed about “Constructors & destructors” in detail. If you need more clarification, just go through that page for the clear understanding of constructors in C++.
[SEE: C Program Tutorials] & [IT Companies Details]
This page also has 2 more example source code of the same era. But here you can find different programming concepts. They are,
- Constructor with Default arguments,
- Power values calculation using constructors.
- Read: Call by Reference programs with example code
In this section we never used any single piece of code about destructors. This is fully for constructors and its operations. Example code is given below for the better understanding.
Constructor with Default Arguments:
#include<iostream.h> #include<conio.h> // Class definition of Cube class C1 { int a, b, c; public: C1(int a1=0, int b1=0, int e1=0) // Default parameter constructor { a=a1; b=b1; c=e1; } int Vlm() // Calculation of Volume { return a*b*c; } }; int main() { clrscr(); C1 x(1,2,5),y; cout<<x.Vlm()<<"\n"; cout<<y.Vlm(); getch(); return 0; }
- Learn [ Aptitude ] - [ Placement Papers ] - [ Spoken English ]
Power values calculation using constructors:
#include<iostream.h> #include<conio.h> // Class POWER value calculation class Pow1 { double m; int t; double V1; public: Pow1(double B, int E); //Constructor with TWO Parameters double inputp() //Function { return V1; } }; Pow1::Pow1(double B, int E) { m=B; t=E; V1=1; if(E==0) return; for( ;E>0;E--) V1=V1*m; } // Main Function int main() { clrscr(); Pow1 p(5.0, 1), j(3.2, 2), v(5.3, 3); cout<<p.inputp()<<" "; cout<<j.inputp()<<" "; cout<<v.inputp()<<"\n"; getch(); return 0; }