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.

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

C++ 8. Constructors and Destructors

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

Special Member Functions

Constructor - example

Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

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

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

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

Constructors for classes



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

CS304 Object Oriented Programming Final Term

CSC1322 Object-Oriented Programming Concepts

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

Object Oriented Design

6.096 Introduction to C++ January (IAP) 2009

Object-Oriented Principles and Practice / C++

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

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

Pointers, Dynamic Data, and Reference Types

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

CMSC 132: Object-Oriented Programming II

G52CPP C++ Programming Lecture 13

Object Oriented Programming in C++ Basics of OOP

class Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

An Introduction to C++

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

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

Review: C++ Basic Concepts. Dr. Yingwu Zhu

OOP THROUGH C++(R16) int *x; float *f; char *c;

[0569] p 0318 garbage

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Written by John Bell for CS 342, Spring 2018


CPSC 427: Object-Oriented Programming

Pointers and Memory 1

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

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

Dynamic Data Structures

04-19 Discussion Notes

Object-Oriented Programming, Iouliia Skliarova

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

CPSC 427: Object-Oriented Programming

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

Assignment of Structs

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:

CHAPTER 4 FUNCTIONS. 4.1 Introduction

TEMPLATES AND EXCEPTION HANDLING

Comp151. Construction & Initialization

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

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

Introduction Of Classes ( OOPS )

Kapi ap l S e S hgal P T C p t u er. r S. c S ienc n e A n A k n leshw h ar ar Guj u arat C C h - 8

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Intermediate Programming & Design (C++) Classes in C++

Object Oriented Programming. Solved MCQs - Part 2

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Chapter 6 Inheritance Extending a Class

CPSC 427: Object-Oriented Programming

Constants, References

G52CPP C++ Programming Lecture 16

INHERITANCE PART 2. Constructors and Destructors under. Multiple Inheritance. Common Programming Errors. CSC 330 OO Software Design 1

CONSTRUCTOR AND DESTRUCTOR

More class design with C++ Starting Savitch Chap. 11

CS304 Object Oriented Programming

For Teacher's Use Only Q No Total Q No Q No

AN OVERVIEW OF C++ 1

CS201- Introduction to Programming Current Quizzes

Vector and Free Store (Vectors and Arrays)

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n

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

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

AIMS Embedded Systems Programming MT 2017

C++ Programming: Polymorphism

Object-Oriented Programming, Iouliia Skliarova

Instantiation of Template class

C++ : Object Oriented Features. What makes C++ Object Oriented

CONSTRUCTORS AND DESTRUCTORS

IS 0020 Program Design and Software Tools

Come and join us at WebLyceum

Programming 2. Object Oriented Programming. Daniel POP

Template Issue Resolutions from the Stockholm Meeting

CS360 Lecture 5 Object-Oriented Concepts

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1

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

More Tutorial on C++:

Pointers. Developed By Ms. K.M.Sanghavi

Object-Oriented Principles and Practice / C++

Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F

C++_ MARKS 40 MIN

Function Overloading

UNIT POLYMORPHISM

Initializing and Finalizing Objects

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

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Constructors & Destructors

CSC 211 Intermediate Programming. Arrays & Pointers

Programming, numerics and optimization

Transcription:

Constructor and Destructor Member Functions Constructor: - Constructor function gets invoked automatically when an object of a class is constructed (declared). Destructor:- A destructor is a automatically called member function of a class, when an object is destroyed of that class. 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. Use of Constructor and Destructor function of a class: - 1. 1.Constructor function is used to initialize member variables to pre-defined values as soon as an object of a class is declared. 2. 2.Constructor function having parameters is used to initialize the data members to the values passed values, upon declaration. Generally, the destructor function is needed only when constructor has allocated dynamic memory. Defining Constructor and Destructor functions The example below illustrates how constructor and destructor functions are defined: 1 / 11

private: int n; Kangra() //constructor n=1; ~Kangra() //destructor ; A few points to note: - Both of the functions have the same name as that of the class, destructor function having (~) before its name. - Both constructor and destructor functions should not be preceded by any data type (not even void). - These functions do not (and cannot) return any values. - We can have only the constructor function in a class without destructor function or vice-versa. - Constructor function can take arguments but destructors cannot. - Constructor function can be overloaded as usual functions. Explicit call to the constructor: - By explicit call to the constructor,means that the constructor is explicitly declared by the programmer inside the class. Implicit call to the constructor: - By implicit call to the constructor,means that the constructor is implicitly provided by the Compiler when an Object of the Class is created and there is no Explicit Constructor defined inside the Class. Example 1: Explicit constructor function to initialize data members to pre-defined values 2 / 11

#include<iostream.h> private: int a; int b; Kangra() //here constructor function is used to initialize data members to pre-defined values a=10; b=10; int add() return a+b; ; int main(void) Kangra obj; cout<<obj.add(); return 0; Example 2: Explicit constructor function to initialize data members to values passed as arguments #include<iostream.h> private: int a; int b; 3 / 11

Kangra(int i, int j)//explicit Constructor with arguments a=i; b=j; int add(void) return a+b; ; int main() myclass obj(10,20); //This Can be written as Kangra obj obj=kangra(10,20); cout<<obj.add(); Default/Implicit constructor: - These constructors are inserted automatically by the Compiler into class declarations that do not have any implicit constructor. Example: class Ayan Ayan() //Default/Implicit Constructor ; 4 / 11

Copy Constructor A copy constructor is a special constructor that creates a new object from an existing object. If we do not define a copy constructor, the compiler will generate one for us that performs a shallow copy (copies only a pointer so that the two pointers refer to the same object) of the existing object's member variables. So, if our object allocates any resources, we most likely need a copy constructor so that we can perform a deep copy (copies what a pointer points to so that the two pointers now refer to distinct objects). // Shallow Copy Example char *ch = new char('z'); char *cp = ch; // copy the pointer ch *ch = 'X'; // change the value of the char pointed to by *ch // Deep Copy Example int *p = new int(99); int *q = new int(*p); // Allocate a new int before copying the value pointed to by p 5 / 11

*p = 100; // change the value of the int pointed to by p Example of Default Copy Constructor that compiler provides and its problem: #include <iostream.h> #include<string.h> int *temp; Kangra(int i) cout << " Constructor"; temp=new int(); *temp = i; ~Kangra() cout << "Destructor"; delete temp; ; int main() Kangra kg(150); // First Object Created Invoke our Constructor Kangra kg1(kg); // Here is the Problem; 6 / 11

/* When Second Object will be Created It will not Invoke our Constructor. It will invoke Default Copy Constructor */ cout << "Main"; return 0; Let's look at the output: Constructor Main Destructor Destructor Null Pointer Assignment Destructor does delete. The problem is it is trying to delete a pointer we haven't allocated. When default copy constructor is called (Kangra kg1(kg)), it does not allocate anything. How to fix it? 7 / 11

Use explicit Copy Constructor Instead of Default Copy Constructor #include<iostream.h> #include<string.h> int *temp; Kangra(int i) cout<<"constructorn"; temp=new int(); *temp=i; Kangra(const Kangra &obj) // Explicit Copy Constructor cout << "Copy Constructorn"; temp = new int(); *temp=*obj.temp ; ~Kangra() cout << "Destructorn"; delete temp; ; int main() Kangra kg(150); // Call to Simple Constructor when Object 1 will be created Kangra kg1(kg); // Call to Explicit Copy Constructor when Object 2 will be created 8 / 11

cout << "Mainn"; return 0; Now we will get the desired output: Two Objects Created and Two Deleted Constructor Copy Constructor Main Destructor Destructor This should be our choice. Summary The copy constructor gets called in the following cases: An object is passed to a method by value or returned by value. 9 / 11

An object is initialized using the syntax, MyClass a = b. An object is thrown or caught in an exception. Constructor with Default Argument: #include <iostream.h> #include<string.h> int temp; Kangra(int i=10) //Constructor with Default Argument 10 cout << " Inside Constructor with Default Argument"; temp=i; cout<<"temp = "<<temp; ; int main() 10 / 11

Kangra kg; // Object Created without argument. This will take default argument of the Constructor cout << "Main"; return 0; Output: Inside Constructor with Default Argument temp=10; Main 11 / 11