Constructors in C++

RubaNagarajan 3,300 views 12 slides Apr 09, 2020
Slide 1
Slide 1 of 12
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12

About This Presentation

concept of constructor and its types


Slide Content

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 ; } };

int main(void) { Add obj1(10, 25);//method 1:for creating object(implicit) Add obj2 = Add(50, 40);// method 2:for creating object(explicit)   return 0; } Output: 35 90

THANK YOU