Recharge (int, int, int); //constructor declared void disply();

Similar documents
3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Constructor - example

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Data Structures using OOP C++ Lecture 3

public : int min, hour ; T( ) //here constructor is defined inside the class definition, as line function. { sec = min = hour = 0 ; }

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Module Operator Overloading and Type Conversion. Table of Contents

Constructors for classes

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe


Introduction Of Classes ( OOPS )

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

C++ 8. Constructors and Destructors

Constructors and Destructors. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Example : class Student { int rollno; float marks; public: student( ) //Constructor { rollno=0; marks=0.0; } //other public members };

Object Oriented Design

Object-Oriented Programming

Evolution of Programming Languages

Chapter 10 Introduction to Classes

Where do we go from here?

Lecture 18 Tao Wang 1

Interview Questions of C++

Object Oriented Programming(OOP).

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

CPSC 427: Object-Oriented Programming

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING REWRAP TEST I CS6301 PROGRAMMING DATA STRUCTURES II

CSC1322 Object-Oriented Programming Concepts

Cpt S 122 Data Structures. Introduction to C++ Part II

Abstraction in Software Development

Classes and Objects. Class scope: - private members are only accessible by the class methods.

G52CPP C++ Programming Lecture 13

AN OVERVIEW OF C++ 1

cout<< \n Enter values for a and b... ; cin>>a>>b;

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

CS304 Object Oriented Programming Final Term

GEA 2017, Week 4. February 21, 2017

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

Make Classes Useful Again

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2

Programming 2. Object Oriented Programming. Daniel POP

Programming in C++: Assignment Week 8

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES III

Short Notes of CS201

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

Object Oriented Design

CS201 - Introduction to Programming Glossary By

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Polymorphism Part 1 1

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

CS3157: Advanced Programming. Outline

Function Overloading

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Inheritance, and Polymorphism.

PESIT Bangalore South Campus

Use the dot operator to access a member of a specific object.

COIMBATORE EDUCATIONAL DISTRICT

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

6.096 Introduction to C++ January (IAP) 2009

Chapter 11. Abstract Data Types and Encapsulation Concepts

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

C++ Basic Syntax. Constructors and destructors. Wojciech Frohmberg / OOP Laboratory. Poznan University of Technology

Constructors & Destructors

Ch. 12: Operator Overloading

Introduction to C++ Friends, Nesting, Static Members, and Templates Topic #7

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

OBJECT ORIENTED PROGRAMMING

Programming in C++: Assignment Week 3

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

COMP 2355 Introduction to Systems Programming

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Intermediate Programming, Spring 2017*

CS201 Some Important Definitions

Object Oriented Design

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

Advanced Systems Programming

Fast Introduction to Object Oriented Programming and C++

The Class. Classes and Objects. Example class: Time class declaration with functions defined inline. Using Time class in a driver.

SFU CMPT Topic: Class Templates

Object-Oriented Programming (OOP) Fundamental Principles of OOP

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13

An Introduction to C++

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

Next week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017

Transcription:

Constructor and destructors in C++ Constructor Constructor is a special member function of the class which is invoked automatically when new object is created. The purpose of constructor is to initialize private data items of the related class. Following are the main features of constructors. Ø Constructor has the same name as is the name of class. Ø Constructors do not have any return type. Ø Constructors are usually declared in public section of the class so that they can be invoked outside the class, when an object is created. Ø Constructors can be private also but private access modifier will hide that constructor from outside the class. Private constructors can be called in class itself and in friend functions only. Ø There can be more than one constructors in a class known as constructor overloading. Ø In case no constructor is defined a default constructor is executed by the compiler. Default customer do not take any parameter. Ø Constructor defined by the programmer may or may not take the parameters. Ø Constructors can also be defined as inline. Ø Constructors can have any type of arguments except its own class type. But the constructor can accept a reference to its own class type object as a parameter. Ø We cannot refer to their address. Program 1: simple constructor with parameters // program to demonstrate how to write and use a constructor #include <iostream> using namespace std; class Recharge int customer_id, amount, validity; ; Recharge (int, int, int); //constructor declared void disply(); // definition of constructor outside the class Recharge :: Recharge (int a, int b, int c) customer_id = a; amount = b; validity = c; Recharge void :: display () cout<< \n...account information of customer... ; cout<< \n customer_id : <<customer_id;

cout<< n amount paid : << amount; cout<< \n validity for : << validity << no. of days ; int main () Recharge cust1( 103, 400, 30); // constructor invoked // implicitly Recharge cust2(205, 200, 10); cust1.disply( ); cust2.display( );...account information of customer... customer_id : 103 amount paid : 400 validity for : 30...account information of customer... customer_id : 205 amount paid : 200 validity for : 10 Types of constructors v Default constructor v Parameterized constructor v Copy constructor Default constructor Any constructor without parameters or when all the parameters have default values is known as a default constructor. It can be auto generated or user defined, but in both the cases it must be called without parameters. If no constructor is defined by the programmer then the compiler implicitly creates a default constructor without body i.e. without any corresponding statement. If there are non-default constructors in the program, then the compiler does not create default constructor. There it is the responsibility of programmer to define default constructor otherwise an error may get generated. Any class can have at the most one default constructor. Default constructors are also known as implicit constructor. Program 2: default constructor with default parameters // program to demonstrate default constructor #include<iosteram> #include<math> class cal_power int n, p; // to use pow() function cal_power ( int a = 10, b = 2); /* default constructor with default arguments*/

void display_result( ) << = << pow(n,p); ; cout<< \n <<n<< raised to the power << p // definition of default constructor --- outside the class cal_power :: cal_power( int a, int b) n = a; p = b; int main ( ) cal_power c1; C1.display_result( ); /* object c1 created using default constructor */ 10 raised to the power 2 = 100 Parameterized constructor This type of constructors are defined with list of arguments. Values for arguments are assigned at the time of creating the objects. Program 1 demonstrates the parameterized constructors. The parameterized constructor can be called implicitly or explicitly, for example v customer_id c1(555, 250, 20); //constructor called implicitly v customer_id c2 = customer_id(111, 300, 21); // constructor called explicitly Copy constructor Copy constructor is used to declare and initialize an object from some already existing object of the class. As discussed above constructors can have any type of arguments except its own class type. But the constructor can accept a reference to its own class type object as a parameter. Copy constructor takes a reference to the object of same class as an argument. Copy constructor cannot accept argument by value. Syntax for copy constructor Example Class_name (class_name & object_name)...body of constructor... Example: customer_id ( customer_id & c ); if there exists a statement like: customer_id cus1( 100,500,25); then following are valid statements to initialize cus2 and cus3 with cus1 customer_id cus2( cus1); customer_id cus3 = cus1;

Constructor overloading A program can have multiple constructors and this concept is called constructor overloading. Program 3: to demonstrate copy constructor and constructor overloading /*C++ program to demonstrate example of Copy Constructor.*/ #include <iostream> using namespace std; class demo private: int X; int Y; ; demo () demo (int a, int b); demo (const demo &d); void display(); //Definition of parameterized constructor. demo:: demo(int a, int b) X = a; Y = b; //Definition of copy constructor. demo:: demo(const demo &d) X = d.x; Y = d.y; // default constructor //parameterized constructor //copy constructor //Definition of display (),the member function. void demo:: display() cout <<"\n X: " << X; cout <<"\n Y: " << Y; int main() demo d1(10,20) ; // creates an object cout<< \n data members of the created object ; cout << \n Object d1 : "; cout<<"values initialized by parameterized constructor: "; d1.display(); /* create and initialize object with other object using copy constructor */

demo d2 = demo(d1); cout<< \n\n object d2, created by copy constructor ; cout << \n Object d2 : " ; cout << "Value initialized by copy constructor : "; d2.display(); data members of the created object Object d1 : Values initialized by parameterized constructor: X: 10 Y: 20 object d2, created by copy constructor Object d2 : Value initialized by copy constructor: X: 10 Y: 20 Copy constructor is used to Ø To initialize an object using another object Ø To copy an object to pass it as an argument by value to a function Ø Also to copy the object to return it from a function by value. Note: If no copy constructor is defined in the class then compiler generates a default copy constructor at its own. Program 4: to demonstrate, when a copy constructor is called by the compiler // program to find sum of two complex numbers #include<iostream> class complex int real, img; complex() // default constructor complex(int r, int i) //parameterized constructor real = r; img = i; complex (complex &c) // copy constructor cout<< \n hi! I m copy constructor here ; real = c.real; img = c.img;

complex sum(complex c); // object as return type void display( ); ; // end of class definition complex complex :: sum(complex c) complex temp; // temporary object created temp.real = real + c.real; temp.img = img + c.img /* real and img in above statements hold data values for the calling object */ return (temp) // returns temp object void complex :: display( ) cout << \n complex number : << real << \t + \t << img i ; //... main function... int main( ) complex c1(5,4); complex c2 = c1; // parameterized constructor invoked //invokes copy constructor // invokes default constructor complex c3; c3 = c1. sum (c2); // please see the note below c1.display( ); c2.display( ); c3.display( ); Note: explanation of statement c3 = c1. sum (c2); Ø Copy constructor is invoked twice in this single statement. Ø c1 is active object here, hence its private data items (real and img) will be used directly i.e without object name and. operator, in the member function sum. Ø c2 is actual argument passed by value to the function. Copy constructor is invoked here to create a copy of c2, the compiler itself calls the copy constructor to create the copy of passed object c2. Ø Compiler once again calls the copy constructor when it encounter the, return(temp); statement in the end of sum function. Here compiler creates unnamed object to hold the value of returned object. hi! I m copy constructor here hi! I m copy constructor here hi! I m copy constructor here complex number : 5 + 10 i

complex number : 5 + 10 i complex number : 10 + 20 i Destructor Destructor functions are inverse of constructor functions. They are invoked automatically when objects are destroyed. An objects gets destroyed when its scope of existence finishes or when the delete operator is used. Like constructor, destructor also follows some rules: Ø Destructors are special member functions of the class and they are used to free the memory allocated to object. Ø Destructors are functions with same name as class and they do not accept any parameters. Even constructors have same name as class, but name of destructor is preceded by ~ (tilde). Ø Like constructor, destructors do not have any return type. Not even void Ø The Destructor of class is automatically called when the object goes out of scope. Ø If there exists no user defined constructor in a class, but is required then the compiler itself declares a destructor implicitly. Ø Destructors cannot be inherited. (will be discussed later) Program 5: to demonstrate the destructor function, how is destructor function declared, defined and invoked /* program to illustrate, automatic execution of constructor and destructor */ #include<iostream> using namespace std; class test char code; test( char c) // constructor defined created ; code = c; cout<< \n object with code = << code << is ~ test ( ) // destructor defined cout<< \n object with code = <<code<< is destroyed ; ; // end of class int main( ) test obj(a), obj(b), obj(c); cout<< \n three object created ; cout<< \n the main program ends here ;

object with code = a is created object with code = b is created object with code = c is created three object created the main program ends here object with code = a is destroyed object with code = a is destroyed object with code = a is destroyed Note: Ø Constructor function is called three times because, three objects are created in first statement of main function. Ø Statements of the main function get executed in the order these are written. Ø Destructor function is called three times (once for each object) just before exiting from the main function.