CONSTRUCTORS AND DESTRUCTORS Chapter 5 By Mrs. Suman Verma PGT (Comp.Sc)

Slides:



Advertisements
Similar presentations
Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Advertisements

Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
Chapter 7: User-Defined Functions II
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
Chapter 14: Overloading and Templates
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Classes: A Deeper Look Systems Programming.
1 Class Constructors a class constructor is a member function whose purpose is to initialize the private data members of a class object the name of a constructor.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
1 Classes and Objects. 2 Outlines Class Definitions and Objects Member Functions Data Members –Get and Set functions –Constructors.
Review of C++ Programming Part II Sheng-Fang Huang.
Chapter 12: Adding Functionality to Your Classes.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
More about Class 靜宜大學資工系 蔡奇偉副教授 ©2011. 大綱 Instance Class Members Class members can be associated with an instance of the class or with the class as a.
CONSTRUCTORS AND THEIR TYPES. Prepared by. MURLI MANOHAR. PGT (COMP
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
WEL COME PRAVEEN M JIGAJINNI PGT (Computer Science) MTech[IT],MPhil (Comp.Sci), MCA, MSc[IT], PGDCA, ADCA, Dc. Sc. & Engg.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Chapter 9 Classes: A Deeper Look, Part I Part II.
 Constructor  Finalize() method  this keyword  Method Overloading  Constructor Overloading  Object As an Argument  Returning Objects.
 A constructor is a special member function whose task is to initialize the objects of its class.  It is special because its name is same as the class.
CONSTRUCTOR AND DESTRUCTORS
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Csi2172 class 5 Midterm: June 12. constructor Special method used to create objects of the class Never has a return type. Is called automatically upon.
OBJECT ORIENTED PROGRAMMING LECTURE 7 Instructor: Rashi Garg Coordinator: Gaurav Saxena.
1 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 10 More on Objects and Classes.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
Classes, Interfaces and Packages
Structs and Classes Structs A struct can be used to define a data structure type as follows: struct Complex { double real, imag;} // specifying a Complex.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Destructors The destructor fulfills the opposite functionality. It is automatically called when an object.
CONSTRUCTOR AND DESTRUCTOR. Topics to be discussed……………….. 1. Introduction Introduction 2. FeaturesFeatures 3. Types of ConstructorTypes of Constructor.
Learners Support Publications Constructors and Destructors.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Object Lifetimes and Dynamic Objects Lecture-7. Object Lifetimes and Dynamic Objects External (Global) Objects Persistent (in existence) throughout the.
Constructors and Destructors
Programming with ANSI C ++
CONSTRUCTORS & DESTRUCTORS
Constructors & Destructors.
Constructor & Destructor
Constructors & Destructors
This pointer, Dynamic memory allocation, Constructors and Destructor
group work #hifiTeam
Prepared by Puttalakshmi H.R PGT(CS) KV Minambakkam Chennai-27.
Constructor & Destructor
CONSTRUCTOR A member function with the same name as its class is called Constructor and it is used to initialize the objects of that class type with.
Contents Introduction to Constructor Characteristics of Constructor
CONSTRUCTORS AND DESRUCTORS
Constructors and destructors
Constructors and Destructors
CS410 – Software Engineering Lecture #5: C++ Basics III
A Deeper Look at Classes
Chapter 9 Introduction To Classes
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
CS148 Introduction to Programming II
Constructors & Destructors
SPL – PS3 C++ Classes.
Presentation transcript:

CONSTRUCTORS AND DESTRUCTORS Chapter 5 By Mrs. Suman Verma PGT (Comp.Sc)

INTRODUCTION The main aim of c++ is to create user defined Data Types such as class. This means that we should be able to initialize a Class type variable (Object) when it is declared and When a variable of built in types goes out of scope,the compiler automatically destroys the variable. C++ provides the special member functions for the above purpose called Constructor and Destructor respectively.

Constructors It is a Special Member function with the same name as its class name. It is used to initialize the objects of that class type with some legal values. It is called itself when the object of that class type is declared. It can be declared within the class as well as outside the class with scope resolution operator.

Example of Constructor A constructor is defined and declared as follows: c lass Student c lass Student { int rollno,marks; int rollno,marks; public: public:.. Student()//Constructor { Rollno=0; Rollno=0; marks=0; marks=0; }.. }; };

NEED FOR CONSTRUCTORS A Constructor for a class is needed so that the compiler automatically initializes an object as soon as it is created. A class constructor,if defined is called whenever a program creates an object of that class. Generally a constructor should be defined under the public sections of the class,so that its objects can be created in any Function Generally a constructor should be defined under the public sections of the class,so that its objects can be created in any Function

TYPES OF CONSTRUCTORS 1 Default Constructor: A Constructor that accepts no arguments or default arguments is called the Default Constructor. In the previous example Student :: Student() is a default constructor.

Example of Default Constructor A default constructor is defined and declared as follows: c lass Student c lass Student { int rollno,marks; int rollno,marks; public: public: Student( ) // Default Constructor Student( ) // Default Constructor { Rollno=0; Rollno=0; marks=0; marks=0; } Student( int a=5, int b= 50 )//Default Constructor { Rollno=a; Rollno=a; marks=b; marks=b; }.. }; };

Significance of Default constructor- These constructors are useful when- We want to create objects without giving initial values. We want to create objects with prescribed initial values. To create the array of objects of the class

For creating the array of objects- Erroneous c lass student { int rollno,marks; int rollno,marks; public: public: student( int a, int b )// Constructor { Rollno = a ; Rollno = a ; marks = b ; marks = b ; }.. }; }; Int main() { student s[5]; //will give error as no default const. present. student s[5]; //will give error as no default const. present. student s1(2, 45);// ok as corresponding const. is there student s1(2, 45);// ok as corresponding const. is there}

For creating the array of objects- Corrected c lass Student { int rollno,marks; int rollno,marks; public: public: Student( ) // Default Constructor Student( ) // Default Constructor { Rollno = 0; Rollno = 0; marks = 0; marks = 0; } Student( int a, int b )// Constructor { Rollno = a ; Rollno = a ; marks = b ; marks = b ; }.. }; }; Int main() { Student s[5]; // OK as default const. present. Student s[5]; // OK as default const. present. Student s1(2, 45);// Ok as corresponding const. is present }

Invocation of Constructors- Invocation of Constructors- In parameterized constructors we must pass the initial values as arguments to the constructor function when an object is declared. This can be done in two ways: 1) By calling the function implicitly e.g: ABC ob1(10,10.5,’a’); 2) By calling the function explicitly ABC ob1=ABC(10,10.5,’a’); //Here ABC is constructor which is called with parameters to create an object ob1.

Temporary Instance When constructor is called explicitly a temporary instance is created. When constructor is called explicitly a temporary instance is created. It is one which lives in the memory as long as it is being used or referenced in an expression and after that it dies. These instances are anonymous i.e. they do not bear name. For example- Class sample { int I,j; public: sample (int a, int b) { i=a; j=b;} void print ( void) {cout<<i<<j<<“\n”;}}; void test (void) { sample s1(2,5); s1.print(); sample(4,9).print();//Temporary instance }

2 Parameterized Constructors: The constructors that can take arguments are called Parameterized Constructors.

Parameterized Constructors Class ABC { int i; int i; Public: Public: float j; float j; char k; char k; ABC( int a, float b, char c) //Parameterized Constructor { i=a; i=a; j=b; j=b; k=c; k=c; }.. };

3. Copy Constructor- This constructor is in the form of Classname(classname& ) The compiler uses this constructor when initialization of one instance takes place with the help of other instance Sample s1; //Default Constructor Sample s2=s1;//Copy Constructor

Copy constructor- A copy const. takes a reference to an object of same class as argument. For example- Class sample { int i,j; public: sample (int a, int b)//parameterized const. { i=a; j=b;} sample (sample & s)//copy const. { i=s.i; j=s.j;} void print ( void) {cout<<i<<j<<“\n”;}}; The const can be used as Sample s1 (4, 5);//paramet. Const is used Sample s2 (s1);// copy const is used Sample s3=s1;// copy const is used

Copy constructor is called when- 1.Object is passed by value 2.A function returns an object Qn- Why the arguments to a copy const. is passed by reference?

Order of constructor Invocation- Sample s1, s2, s3; The sequence of const. invocation will be S1, s2, s3. But in nested class the const. of nested class is called first followed by enclosing class. For example Class student { }; Class subject { }; Class admission { student s1; subject sb1; }; Void main() { admission ad; } The sequence of const. invocation will be ???? ????

DYNAMIC CONSTRUCTORS The constructors can also be used to allocate memory while creating objects.This will enable the system to allocate right amount of memory for each object when the objects are not of same memory. Allocation of memory to objects at the time of their construction is known as dynamic construction of objects. The memory is allocated with the new operator.

Constructor Overloading A class having no. of constructors with different no. or type of arguments is called to be overloaded. This process is called function overloading.

Characteristics of Constructors They are invoked automatically when the objects are created. They do not have return types, not even void and therefore they cannot return values. They cannot be inherited, though a derived class can call the base class constructor. Like other c++ functions, they can have default arguments. They should be declared in the public section.

Destructors A destructor is a member function which is used to destroy the objects that have been created by a constructor. Like a Constructor, the destructor is a member function whose name is the same as the class name but preceded by a tilde. For example,the destructor for the class can be defined as shown below: For example,the destructor for the class can be defined as shown below: ~student(){ } ~student(){ }

Example of Destructor A destructor is defined and declared as follows: Class sample Class sample { int i,j; int i,j; Public: Public:.. Sample(int a,int b)//Constructor { i=a; i=a; j=b; j=b; } ~Sample() //Destructor { cout<<“Destructor at work”; cout<<“Destructor at work”; }. }; };

NEED FOR DESTRUCTORS During the construction of an object by the constructor, resources are allocated for use e.g.,allocation of memory, opening of file etc. these allocated resources must be deallocated before the object is destroyed. A destructor is responsible for this task and performs all clean up jobs like closing a file, deallocating and releasing memory area automatically.

Characteristics of Destructors Destructor functions are invoked automatically when the objects are destroyed. Destructor functions also, obey the usual access rules as other member functions do. No argument can be provided to a destructor, neither does it return any value. They can’t be inherited. A destructor may not be static. Member functions may be called from within a destructor.

Problem 1. Explain Constructors and Destructors with Example. 1. Explain Constructors and Destructors with Example. 2. Explain the advantages of function overloading over default arguments.