CONSTRUCTORS IN C++ BY N.RUBA ASST.PROF/DEPT. OF CA, BONSECOURS COLLEGE FOR WOMEN, THANJAVUR.
Constructor is a special member function of a class that initializes the object of the class. Constructor name is same as class name and it doesn’t have a return type. Constructors in C++
#include < iostream > using namespace std ; class number { public: int num ; char ch ; number() { num = 100; ch = 'A'; } }; Simple Example: How to use constructor in C++
int main() { Number obj ;// create the object of class, cout <<" num : "<< obj.num << endl ;// access data //members using object cout <<" ch : "<<obj.ch; return 0; } Output: num : 100 ch : A Contd --
Constructor is different from member function of the class. 1) Constructor doesn’t have a return type. Member function has a return type. 2) Constructor is automatically called when we create the object of the class. Member function needs to be called explicitly using object of class. 3) When we do not create any constructor in our class, C++ compiler generates a default constructor and insert it into our code. The same does not apply to member functions. Constructor vs Member function
This is how a compiler generated default constructor looks: class XYZ { .... XYZ() { ---- } }; Contd --
There are two types of constructor in C++. 1) Default constructor 2) Parameterized constructor 1) Default Constructor A default constructor doesn’t have any arguments (or parameters) #include < iostream > using namespace std ; class Website{ public: //Default constructor Website() { cout <<"Welcome to Bonsecours "<< endl ; } }; Types of Constructor in C++
int main(void){ Website obj1;// creating two objects of class Website. Website obj2;// constructor should have been invoked twice. return 0; } Output: Welcome to Bonsecourss Welcome to Bonsecours When you don’t specify any constructor in the class, a default constructor with no code (empty body) would be inserted into your code by compiler. Contd --
Constructors with parameters are known as Parameterized constructors. These type of constructor allows us to pass arguments while object creation. Parameterized Constructor: XYZ( int a, int b) { } ... XYZ obj (10, 20); Parameterized Constructor
Example: #include < iostream > using namespace std ; class Add { public: Add( int num1, int num2) //Parameterized constructor { cout <<(num1+num2)<< endl ; } };