Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.

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.
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
C++ Programming: Program Design Including Data Structures, Third Edition 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];
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Constructors & Destructors Review CS 308 – Data Structures.
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.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt Constructors and Destructors.
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
C++ Review (3) Structs, Classes, Data Abstraction.
Chapter 10 Introduction to Classes
Concordia TAV 2002 Comp5421_421 Comp5421 Object Oriented Programming Using C++ Efficiently Lecture 4 (2) Tianxiang Shen Summer 2002 Department of Computer.
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.
Copyright 2008 Oxford Consulting, Ltd 1 October C++ Classes Enhanced Structures C  struct only permitted to have data members  Functions to.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
CONSTRUCTORS AND DESTRUCTORS Chapter 5 By Mrs. Suman Verma PGT (Comp.Sc)
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:
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
 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.
CSI 3125, Preliminaries, page 1 Class. CSI 3125, Preliminaries, page 2 Class The most important thing to understand about a class is that it defines a.
OBJECT ORIENTED PROGRAMMING LECTURE 7 Instructor: Rashi Garg Coordinator: Gaurav Saxena.
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.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Classes II Lecture 7 Course Name: High Level Programming Language Year : 2010.
CONSTRUCTOR AND DESTRUCTOR. Topics to be discussed……………….. 1. Introduction Introduction 2. FeaturesFeatures 3. Types of ConstructorTypes of Constructor.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
Learners Support Publications Constructors and Destructors.
Constructors And Destructors. 2 Constructor Special Member Function used for Initialization -- Same Name as the Class Name Special Member Function used.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
Constructors and Destructors
Static data members Constructors and Destructors
By Muhammad Waris Zargar
CONSTRUCTORS & DESTRUCTORS
Java Primer 1: Types, Classes and Operators
Constructors & Destructors.
CS410 – Software Engineering Lecture #11: C++ Basics IV
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
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Constructors & Destructors
Presentation transcript:

Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND

 Class  Structure of a Class  Constructor  Types of Constructor  Default Constructor  Parameterized Constructor  Destructor  An example  Conclusion

 A class is a group of objects that share common properties and relationships.  Class is a structure for implementing real world objects using any object based or object oriented programming language.  Class creates only the definition for objects.  Class is the combination of data members (characteristics) and member functions (behaviors) for the object.

class Student { private: int AdmNo, RollNo; char Name[30], ClassName; public: void InsertData(void); void ShowData(void); } S1, S2; Keyword Name of the Class Access Specifiers Data Members Object ListMember Functions

Constructors  A constructor is a special member function with the same name as its class name.  It is called constructor because it constructs the values of data members of the class.  The constructor is invoked whenever an object of its associated class is created.  It invokes automatically by the C++ compiler, when an object is created.  Use- It is used to initialize the object of the class type with a legal initial value.

class add { int m, n ; public : add (void) ; }; add :: add (void) { m = 0; n = 0; }  When a class contains a constructor, it is guaranteed that an object created by the class will be initialized automatically.  add a ;  Not only creates the object a of type add but also initializes its data members m and n to zero.

 There is no need to write any statement to invoke the constructor function.  If a ‘normal’ member function is defined for zero initialization, we would need to invoke this function for each of the objects separately.  A constructor that accepts no parameters is called the default constructor.  The default constructor for class A is A : : A ( ) continue …

 They are invoked automatically when the objects are created.  All the objects of the class having a constructor are initialized before some use.  These should be declared in the public section for availability to all the functions  They do not have return types, not even void and they cannot return values.  They cannot be inherited, though a derived class can call the base class constructor.

 We can not refer to their addresses.  An object with a constructor (or destructor) can not be used as a member of a union.  They make ‘implicit calls’ to the operators new and delete when memory allocation is required.  When a constructor is declared for a class initialization of the class objects becomes mandatory.  Like other C++ functions, Constructors can have default arguments.  Constructors can not be virtual.

1. These cannot be static. 2. Default and copy constructor are generated by the compiler whenever required. Generated constructors are public. 3. Constructors can have default argument as other C++ functions. 4. A constructor can be used explicitly to create new objects it class type, using the syntax Class-name(expression-list) 1. Sample obj1=Sample(13,22.42);

Constructor may be of following types:  Default constructor  User defined constructor  Parameterized construc tor  Copy Constructor

 It is also created by the user but it has some values that can be passed for initializing the data members.  This is achieved by passing arguments to the constructor function when the objects are created.  Parameter values are passed from the caller function with the object followed by the parentheses.  The constructors that can take arguments are called parameterized constructors.

 The syntax is: ( ) { // Data members values // Initialization statements } For parameterized constructor (parameter list) { // Data members values // Initialization statements }

class add { int m, n ; public : add (int, int) ; }; add : : add (int x, int y) { m = x; n = y; } moid main() { add sum(100,200); }  When a constructor is parameterized, we must pass the initial values as arguments to the constructor function when an object is declared.  Two ways Calling: o Explicit  add sum = add(2,3); o Implicit  add sum(2,3)  Shorthand method

 When there is no any constructor defined in the class by the user, then this constructor is used.  It is invoked by the C++ compiler for creating the space for data members and the compiler fills data members with garbage values.  A constructor that accept no parameter is called the default constructor.  You can’t create an array of objects unless your class has a default constructor( implicitly or explicitly defined)

class Test{ int a;char b; Public: Test(int I,char j) {a=I;j=b; } }; void main() { Test Tarray[5]; //wrong Test newobj(31,’z’); //ok } class Test{ int a;char b; Public: Test(){ cout<<“Default constructor \n”;} Test(int I,char j) {a=I;j=b; cout<<“parameterized constructor \n”; } }; void main() {Test Tarray[5]; Test newobj(31,’z’); }

Temporary Instances The explicit call to a constructor also allows you to create a temporary instance or temporary object. A temporary instance is the one that lives in the memory as long as it is being used or referenced in an expression and after this it dies.

class Sample{ int i,j; public:Sample(int a,int b) {i=a;j=b;} void print(voit){ cout<<i<<j<<“\n”; } }; void test(void) { Sample S1(2,5); S1.print(); Sample(4,9).print();//data values of atemporary.

 It is a member function which initializes an object using another object of the same class If you have not defined a copy constructor, the complier automatically creates it and it is public  Copy constructor always takes argument as a reference object.  We cannot pass the argument by value to a copy constructor.  A copy constructor has the following general function prototype: class_name (const class_name&); Consider the following class definition

class sample { int i, j; public: sample ( int a, int b) { i = a; j = b; } sample ( sample & s) { i = s.i ; j = s.j ; } void print(void) { cout<<i <<“ “<<j <<“\n”; } Above constructors may be used as follows sample s1 (10,12); //1 st const. called sample s2 (s1) // copy const. called sample s3 = s1; copy const. called

=> When is a copy constructor called? 1. When an object is passed by a value: The copy constructor is invoked when an object is passed by values to a function. the pass-by value method requires a copy of the passed argument to be created for the function to operate upon. void afunc(Sample); //Sample is a class afunc(obj1); // Obj1 is an object of Sample type. 2. When a function return an object: Sample afun( ); //prototype Obj2=afun( );//copy constructor invoked

Q. Why the argument to a copy constructor is passed by reference ? Order of Constructor Invocation  The objects are constructed in the order they are defined. Consider the following statement  Sample s1,s2,s3; // the order of construction is s1,s2,s3.  But when a class containing objects of another class as its members. In such a case, the constructor for member objects are invoked first and then only, the constructor for containing class is invoked.  For example

class A { public: A() { cout<<“Constructing A” <<endl; }}; class B { public: B() { cout<<“Constructing B” <<endl; }}; class C { private: A objA; B objB; public: C() { cout<<“Constructing C” <<endl; }}; int main() { clrscr(); C objC; getch(); }

 Providing initial value to objects at run time.  See the text book example:5.2.9  Advantage –  We can provide various initialization formats, using overloaded constructors.  This provides the flexibility of using different format of data at run time depending upon the situation.

 Same as member functions ovelaoding

=>A destructor has the same name as the class but is preceded by a tilde (~) => It is used to de-allocate or free the memory used by the object.  It is better to include a destructor for a class.  A destructor has normally no function body.  ~ integer ( ) { }  A destructor should be defined under the public sector of a class. so that its objects can be (used and then ) destroyed in any function

 A destructor never takes any argument nor does it return any value.  It will be invoked implicitly by the compiler upon exit from the program – or block or function as the case may be – to clean up storage that is no longer accessible.  It is a good practice to declare destructors in a program since it releases memory space for further use.  Whenever new is used to allocate memory in the constructor, we should use delete to free that memory.

The syntax for creating a destructor is: ~ ( ) ‏ { } Tilde symbol indicating that a destructor is defined here.

class Book { private: int NoOfPages, Volume; char Name[30], Author[30], Publisher[30]; public: //Constructor Book ( ) { NoOfPages=100; Volume=1; } //Parameterized Constructor Book (int NP, int Vol) { NoOfPages=NP; Volume=Vol; } // Destructor ~Book ( ) { } void GetShowBookData( ); };

=>A destructor function is called automatically when the object goes out of scope(destroyed): (1) the function ends (2) the program ends (3) a block containing temporary variables ends (4) a delete operator is called => Only one destructor for a class. in other word, destructors can’t be overloaded. => If a class has a destructor, each object of the class will be de-initialized before the object goes out of scope(Local objects at the end of the block defining them and global and static object at the end of the program). => no arguments and return no values. => It can’t be inherited => A destructor may not be static.

=>It is not possible to take the address of a destructor. => Member functions may be called from within a destructor. => An object of a class with a destructor cannot be a member union. =>If you do not specify a destructor, the compiler generates a default destructor for you.

 Constructor and destructor are special functions.  They are used to allocate and de-allocate memory for objects.  They are called special functions because they share common name between the class and themselves.  Constructor and Destructor are always created in the public area of a class.  They can also be used at the time of inheritance.

END