CONSTRUCTORS AND DESRUCTORS

Slides:



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

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.
Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Classes and Objects. Class  A class is a way to bind the data describing an entity and its associated functions together.  In C++ class makes a data.
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];
Road Map Introduction to object oriented programming. Classes
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
Review of C++ Programming Part II Sheng-Fang Huang.
XII CBSE Previous Year Question Paper QUESTION NO 2 (b) 2 Marks.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
CONSTRUCTORS AND THEIR TYPES. Prepared by. MURLI MANOHAR. PGT (COMP
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Chapter 10 Introduction to Classes
 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.
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:
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
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.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
OBJECT ORIENTED PROGRAMMING LECTURE 7 Instructor: Rashi Garg Coordinator: Gaurav Saxena.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
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.
Constructors and Destructors
Chapter 7: User-Defined Functions II
Static data members Constructors and Destructors
By Muhammad Waris Zargar
Programming with ANSI C ++
Constructors & Destructors.
About the Presentations
Constructor & Destructor
Constructors & Destructors
This technique is Called “Divide and Conquer”.
Student Book An Introduction
Programmazione I a.a. 2017/2018.
Lecture 4-7 Classes and Objects
Prepared by Puttalakshmi H.R PGT(CS) KV Minambakkam Chennai-27.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Constructor & Destructor
Chapter 9 Classes: A Deeper Look, Part 1
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.
Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes
Contents Introduction to Constructor Characteristics of Constructor
Dr. Bhargavi Dept of CS CHRIST
Constructors and destructors
Constructors and Destructors
Classes and Objects.
CPS120: Introduction to Computer Science
COP 3330 Object-oriented Programming in C++
9-10 Classes: A Deeper Look.
Java Programming Language
CS410 – Software Engineering Lecture #5: C++ Basics III
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Constructors & Destructors
More C++ Classes Systems Programming.
9-10 Classes: A Deeper Look.
CMSC 202 Constructors Version 9/10.
Presentation transcript:

CONSTRUCTORS AND DESRUCTORS Pradeep Swami KV Jhunjhunu 9649088838

INTRODUCTION The most important OOP features are not only implemented but also tied together by the single most important C++ enhancement, a CLASS. But definition of class only creates a data type. The objects of a class type have to be created and initialized separately as an object. An object, in effect, is a region of memory storage, created at run time. C++ provides a mechanism for initializing an object when it is created (Constructors) and when the same is not needed, C++ defines a way to scrap it off, by means of a destructors.

CONSTRUCTORS A member function with the same name as its class is called Constructor. Constructors are called automatically when an object is created of that class. Constructors are used to initialize the object to a legal initial value for the class. The have no return type, not even void.

EXAMPLE class student { private: int rollno; float marks; public: . student( ) // constructor rollno= 0; marks= 0.0; } }; // Now forth, whenever an object of the student type will be created , the compiler will automatically call the constructor student :: student( ) for the newly constructed object.

NEED FOR CONSTRUCTORS { int rollno; float marks; }; int main( ) { A structure or an array in C++ can be initialized at the time of their declaration. e.g. struct student { int rollno; float marks; }; int main( ) { student s1=(0,0.0); int a[5] = {1,2,3,4,5}; }

But such initialization does not work for a class because the class members have their associated access specifiers. They might not be available to the outside world. e.g. class student { private: int rollno; float marks; public: ___________ // public members ___________ }; int main( ) { student s1=(0,0.0); // illegal ! }

student s1; // create an object s1.init( ); // initialize it There is an alternative solution to it. If we define a member function (say init() ) inside the class to provide the initial values, as shown below: class student { private: int rollno; float marks; public: void init( ) { rollno=0; marks=0.0; } }; int main( ) student s1; // create an object s1.init( ); // initialize it

See now the function init( ) can provide initial values, but still the programmer has to explicitly invoke it. What if, the programmer fails to invoke init( ) ? The object in this case, is full of garbage and might cause havoc in your program. Then what is the way out? Simple, take the responsibility of initialization away from the programmer and give it to the compiler. Every time the object is created, the compiler will automatically initialize it by invoking the initialization function. And that is, you know it ,a Constructor!

DEFAULT CONSTRUCTOR A constructor that accepts no parameter is called the default constructor. With a default constructor ,objects are created just the same way as variables of other data types are created. e.g. X obj1; will create the object obj1 of type X by invoking the default constructor. If a class has no explicit constructor defined, the compiler will supply a default constructor. The default constructor provided by the compiler does not do anything specific. It simply allocates memory to data members of object.

PARAMETERIZED CONSTRUCTORS Like other functions you can also write constructors that can accept parameters. Such constructors are called parameterized constructed (or regular constructors). Once you declare a constructor with arguments, the default constructor becomes hidden. You cannot invoke it. A constructor with default arguments is equivalent to a default constructor.

class A { int i; float j; public: A (int a=0, float b=100.0); // prototype declaration with }; default arguments A::A (int a, float b) // constructor definition { i=a; j=b; } int main( ) { A obj1 (23,2715.50); // values passed for obj1 A obj2;

SIGNIFICANCE OF DEFAULT CONSTRUCTORS The default constructors are very useful when you want to create objects without having to type the initial values or want to initialize objects every time with pre specified initial values or if you want to create an array of objects. You cannot create array of objects unless your class has a default constructors.

// code snippet 1: Default constructor not available class test { int a; char b; public: test ( int i , char j) //This is not default constructor { a=i ; b=j ; } }; int main( ) { test tarray [5]; //Error! (as array can’t be created because default constructor is not available) test newobj ( 31,‘z’); //Valid as corresponding constructor // accepting the arguments is available.

// code snippet 2: Default constructor is available class test { int a; char b; public: test ( ) //THIS IS DEFAULT CONSTRUCTOR { cout<< “Default constructor being called”; } test ( int i , char j) //Constructor with arguments { a=i ; b=j ; cout<< “Constructor with arguments called”; }; int main( ) { test tarray [5]; //Valid! (as array can be created because default constructor is available) test newobj ( 31,‘z’); // constructor with arguments will be called

INVOCATION OF CONSTRUCTORS With a parameterized constructors for a class, one must provide initial values as arguments, otherwise, the compiler will report an error. e.g. ABC obj1; //invalid will cause an error as no argument value has been supplied at the time of object declaration. Constructors can be invoked in two ways: 1. IMPLICITLY e.g ABC obj1(13,11.4,‘p’); Also known as shorthand method. 2. EXPLICITLY e.g ABC obj1= ABC(13,11.4,‘p’);

TEMPORARY INSTANCES The explicit call to the constructor also allows you to create a temporary instance or 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. The temporary instances are anonymous i.e they do not bear a name. e.g sample obj1(2,5); //an object obj1 created obj1.print( ); sample(4,9).print( );

COPY CONSTRUCTOR sample s1; //default constructor used sample s2=s1; //copy constructor used In the above code, for the second statement, compiler will copy the instance s1 to s2 member by member . If you have not defined a copy constructor, the compiler automatically, creates it and it is public. The process of initializing through copy constructor is known a copy initialization. You can create your copy constructor also.

class sample { int i , j ; public: sample (int a , int b) //constructor { i=a; j=b; } sample (sample & s) // copy constructor { j= s.j ; i=s.j ; cout<<“Copy constructor working”; } void print (void) { cout<<i<<j; } };

one parameterized and other copy constructor. This code has two constructors: one parameterized and other copy constructor. These constructors may be used as: sample s1(4,a); sample s2(s1); //s1 copied to s2 sample s3=s1; //s1 copied to s3 But s4=s1; will not invoke the copy constructor. However, if s4 and s1 are objects of same type, this statement is valid and simply assigns values of s1 to s4,member by member.

CONSTRUCTOR OVERLOADING Just like any other function, the constructor of a class may also be overloaded so that even with different number and types of initial values, an object may still be initialized. Overloaded member functions may be used to set or return values in a class. Example in C++

OVERLOADING vs DEFAULT ARGUMENTS Advantages of function overloading over default arguments: Default arguments may not work for all possible combinations of arguments whereas a function may be overloaded for all possible combinations of arguments. With function overloading, multiple function definitions can be executed but with default arguments exactly one function is executed. By declaring an overloaded function, you save the compiler from the trouble of pushing the default argument value on the function call stack, and you save the function from the trouble of testing the default value.

DESTRUCTORS class sample { int i , j ; public: A Destructor is also a member function whose name is the same as the class name but preceded by tilde (‘~’). e.g. class sample { int i , j ; public: sample (int a , int b) //constructor { i=a; j=b; } ~ sample( ) { cout<<“Destructor”; } }; int main( ) { sample s1(3,4); --------- // automatically s1 is destructed at the end of the block using destructor ~ sample( ) }

CHARACTERISTICS OF DESTRUCTORS Invoked automatically when objects are destroyed. You can have only one destructor in a class. i.e. Destructors can’t be overloaded. Each object of the class will be deinitialized before the object goes out of scope.( Local objects at the end of the block defining them and global objects at the end of the program. They also follow access rules. No argument can be provided to a destructor, neither does it return any value. They cannot be inherited. It is not possible to take the address of a destructor. Member functions may be called from within the destructor.

Assignment

Q1: What is copy constructor Q1: What is copy constructor? Give an example in C++ to illustrate copy constructor. Q2: Differentiate between Constructor and Destructor function in context of classes and objects using C++. Q3:Answer the questions based on this Program: class retail { char category[20],item[20]; int qty; float price; retail( ) // Function 1 { strcpy (category, “Cereal”); strcpy (item, “rice”); qty=100; price=25; } public:

void show( ) // Function 2 { cout<<category<<“-”<<item<<“:”<<qty << “@” <<price<<endl; } }; void main( ) { retail r; // statement 1 r.show( ); // statement 2 Will statement 1 initialize all the data members for object r with the values given in the function 1? (Yes or NO). Justify your answer suggesting the correction's to be made in the above code. What will be the output ? (assuming corrections are made)

Q4: Define a class clothing in c++ with the following descriptions: Private members: code of type string type of type string size of type integer material of type string price of type float A function calc_price( ) which calculates and assigns the value of price as follows: For the value of material as “COTTON”:

TYPE PRICE (Rs) trouser 1500 shirt 1200 For materials other than “COTTON” the above mentioned Price gets reduced by 25%. Public Members: A constructor to assign the initial values of code, type and material with the “NOT ASSIGNED” and size and price with 0. A function enter( ) to input the values of the data members code , type ,size and material to invoke the calc_price( ) function. A function show( ) which displays the content of all the data members for a clothing.

Q5: Describe the importance of destructor. Q6: How many times is the copy constructor called in the following code? sample func (sample u) { sample v(u); sample w=v; return w; } void main( ) { sample x; sample y= func(x); sample z= func(y);