From PU/ Object Oriented Programming in C++
Asked on 24 Mar, 2020
0
856 Views
Constructor function is called implicitly (automatically) when new objects of a class are created. So, by this feature, we wont have to call some functions for initialization of objects every time we create them by having compiler do this for us by default using constructors.
Sample Example:
Without Constructors:
class Square{
public:
int len ;
void init(){ len = 0 ; cout << "initialized" ; }
void read(){
cout << "enter side: " ; cin >> len ; }
void showArea(){ cout << "Area: "<< len * len ; }
}
main(){
Square s1, s2 ;
//Here, we have to call init() and read() method every time we create objects of Square Class.
s1. init() ; s2.init() ;
s1.read(); s2.read() ;
s1.showArea(); s2.showArea() ;
}
With Constructors:
class Square{
public:
int len ;
void init(){ len = 0 ; cout << "initialized" ; }
void read(){cout << "enter side: " ; cin >> len ; }
void showArea(){ cout << "Area: "<< len * len ; }
//Adding Constructor function
Square(){
// Calling default functions for initialization inside ctor
init() ;
read() ;
}
}
main(){
Square s1, s2 ;
//Here, we dont have to call init() and read() method every time we create objects of Square Class, since they will be called automatically from the constructor function.
s1.showArea(); s2.showArea() ;
}
Add your answer