Constructors & Destructors

Slides:



Advertisements
Similar presentations
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.
Advertisements

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.
Short C++ Review CS 302 – Data Structures. Call by value/reference.
Constructors & Destructors Review CS 308 – Data Structures.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
Introduction to C++ Programming
Operator Overloading CS 308 – Data Structures What is operator overloading? Changing the definition of an operator so it can be applied on the objects.
Review of C++ Programming Part II Sheng-Fang Huang.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
C++ Review CS 302 – Data Structures Review Topics Calling functions by value or reference Pointers and reference variables Static and dynamic arrays.
Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt Constructors and Destructors.
CONSTRUCTORS AND THEIR TYPES. Prepared by. MURLI MANOHAR. PGT (COMP
 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.
CONSTRUCTOR AND DESTRUCTORS
1 CS161 Introduction to Computer Science Topic #16.
OBJECT ORIENTED PROGRAMMING LECTURE 7 Instructor: Rashi Garg Coordinator: Gaurav Saxena.
Constructors & Destructors, Proxy Classes, Friend Function and example of static member.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Destructors The destructor fulfills the opposite functionality. It is automatically called when an object.
Classes II Lecture 7 Course Name: High Level Programming Language Year : 2010.
Constructors, Copy Constructors, constructor overloading, function overloading Lecture 04.
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
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Learning Objectives Pointers as dada members
Access Functions and Friend Functions
Overloading Operator MySting Example
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Default Constructors A default constructor is a constructor that takes no arguments. If you write a class with no constructor at all, C++ will write a.
Programming with ANSI C ++
CSC241: Object Oriented Programming
CONSTRUCTORS & DESTRUCTORS
CISC181 Introduction to Computer Science Dr
Concepts of Constructors and Its Types
Constructors & Destructors.
Introduction to Classes
Chapter 5 Classes.
Constructor & Destructor
This pointer, Dynamic memory allocation, Constructors and Destructor
group work #hifiTeam
Lecture Constructors and Destructors
Prepared by Puttalakshmi H.R PGT(CS) KV Minambakkam Chennai-27.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Constructor & Destructor
Introduction to Classes
CS212: Object Oriented Analysis and Design
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
Constructor Spl member fn auto ini of object
Constructors and destructors
Constructors and Destructors
Constructors and Destructors
9-10 Classes: A Deeper Look.
Introduction to Classes and Objects
CS410 – Software Engineering Lecture #5: C++ Basics III
A Deeper Look at Classes
Review: C++ class represents an ADT
Destructors, Copy Constructors & Copy Assignment Operators
Destructors, Copy Constructors & Copy Assignment Operators
Constructors & Destructors
More C++ Classes Systems Programming.
CS 144 Advanced C++ Programming April 30 Class Meeting
9-10 Classes: A Deeper Look.
Presentation transcript:

Constructors & Destructors

What is a constructor? It is a special type of member function whose task is to initialize the objects of the class. A constructor has: (i) the same name as the class itself (ii) no return type

class marks { int n, m; public: marks() n=12;m=13; } void add() cout<<(n+m); }; void main() marks ob; ob.add();

Comments on constructors A constructor is called automatically whenever a new instance of a class is created. You must supply the arguments to the constructor when a new instance is created. If you do not specify a constructor, the compiler generates a default constructor for you (expects no parameters and has an empty body).

Special characteristics of constructors They should be declared in the public section. They are invoked automatically when the objects are created. They should not have return types, not even void and therefore can’t return values. They can’t be inherited through a derived class. They can have default arguments.

Comments on constructors (cont.) void main() { rectangle rc(3.0, 2.0);   rc.posn(100, 100); rc.draw(); rc.move(50, 50); } Warning: attempting to initialize a data member of a class explicitly in the class definition is a syntax error.

Parameterized Constructor In order to initialize various data elements of different objects with different values when they are created. C++ permits us to achieve this objects by passing argument to the constructor function when the object are created . The constructor that can take arguments are called parameterized constructors

class abc { int m, n; public: abc (int x, int y); // parameterized constructor ................ ................. }; abc : : abc (int x, int y) { m = x; n = y; }

class book { int price; int year; public: book(int x, int y); void putdata(); book(); }; book::book(int x, int y) price=x; year=y; } void book::putdata() cout<<"price is"<<price<<"\n"; cout<<"year is"<<year<<"\n";

book::book() { price=0; year=0; } int main() book b1,b2(10,50); b1 book::book() { price=0; year=0; } int main() book b1,b2(10,50); b1.putdata(); b2.putdata(); getch();

Multiple Constructors in a class

class marks { int n, m; public: marks() n=0; m=0; } marks(int x,int y) n=x; m=y; void add() cout<<(n+m); }; void main() marks ob(4,5); ob.add();

Copy Constructor A copy constructor is a special constructor in the C++ programming language used to create a new object as a copy of an existing object. The first argument of such a constructor is a reference to an object of the same type as is being constructed (const or non-const), which might be followed by parameters of any type (all having default values).

Copy Constructor Copying of objects is achieved by the use of a copy constructor and an assignment operator. A copy constructor has as its first parameter a (possibly const or volatile) reference to its own class type. It can have more arguments, but the rest must have default values associated with them.

Copy constructor It is a member function which initializes an object using another object of the same class. A copy constructor has the following general function prototype:  class_name (const class_name&);

#include<iostream #include<iostream.h> Class code { int id; Public: code() { } code(int a) { id = a; } code (code & x) { id = x. id; } void display() { cout<<id; } }; Int main() code A(100); code B(A); code C = A; code D; D = A; A.display(); B.display(); C.display(); D.display(); return 0; }

Defining copy constructors is very important In the absence of a copy constructor, the C++ compiler builds a default copy constructor for each class which is doing a memberwise copy between objects. Default copy constructors work fine unless the class contains pointer data members ... why???

void string::copy(char void string::copy(char *c) { strcpy(s, c); } void main() string str1("George"); string str2 = str1; // default copy constructor str1.print(); // what is printed ? str2.print(); str2.copy("Mary"); str1.print(); // what is printed now ?

Defining a copy constructor for the above example: class string { private: char *s; int size; public: string(char *); // constructor ~string(); // destructor string(const string&); // copy constructor void print(); void copy(char *); };

string::string(const string& old_str) size = old_str.size; { size = old_str.size; s = new char[size+1]; strcpy(s,old_str.s); }   void main() string str1("George"); string str2 = str1; str1.print(); // what is printed ? str2.print(); str2.copy("Mary"); str1.print(); // what is printed now ? Note: same results can be obtained by overloading the assignment operator.

Following cases may result in a call to a copy constructor When an object is returned by value When an object is passed (to a function) by value as an argument When an object is thrown When an object is caught When an object is placed in a brace-enclosed initializer list

Dynamic Constructor The constructors can also be used to allocate memory while creating objects. This will enable the system to allocate the right amount of memory for each object when the objects are not of the same size, thus resulting in the saving of 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 help of new operator

# include <iostream. h> # include <conio # include <iostream.h> # include <conio.h> # include <string.h> class str { char *name; int len; public: str() len=0; name=newchar[len+1]; } str(char *s) len=strlen(s); strcpy(name,s); void show() { cout<<"NAME IS:->"<<name<<endl; void join(str &a,str &b); };

void str::join(str &a,str &b) { len=a. len+b void str::join(str &a,str &b) { len=a.len+b.len; delete new; name=newchar[len+1]; strcpy(name,a.name); strcat(name,b.name); };

void main() { clrscr(); char void main() { clrscr(); char *first="HARSHIL"; str n1(first), n2("NINAD"), n3("PRATIK"), n4, n5; n4.join(n1,n2); n5.join(n4,n3); n1.show(); n2.show(); n3.show(); n4.show(); n5.show(); }

Composition: objects as members of classes A class may have objects of other classes as members.   class properties { private: int color; int line; public: properties(int, int); // constructor }; properties::properties(int c, int l) { color = c; line = l; }

Composition: objects as members of classes (cont.) class rectangle { private: float height; float width; int xpos; int ypos; properties pr; // another object public: rectangle(float, float, int, int ); // constructor void draw(); // draw member function void posn(int, int); // position member function void move(int, int); // move member function };

Composition: objects as members of classes (cont.) rectangle::rectangle(float h, float w, int c, int l):pr(c, l) { height = h; width = w; xpos = 0; ypos = 0; }; void main() rectangle rc(3.0, 2.0, 1, 3); C++ statements; }

What is a destructor? It is a member function which deletes an object. A destructor function is called automatically when the object goes out of scope: (1) the function ends (2) the program ends (3) a block containing temporary variables ends (4) a delete operator is called  A destructor has: (i) the same name as the class but is preceded by a tilde (~) (ii) no arguments and return no values

class string { private: char. s; int size; public: string(char class string { private: char *s; int size; public: string(char *); // constructor ~string(); // destructor }; string::string(char *c) { size = strlen(c); s = new char[size+1]; strcpy(s,c); } string::~string() delete []s;

Comments on destructors If you do not specify a destructor, the compiler generates a default destructor for you. When a class contains a pointer to memory you allocate, it is your responsibility to release the memory before the class instance is destroyed.

#include <iostream. h> #include <string #include <iostream.h> #include <string.h> class string { private: char *s; int size; public: string(char *); // constructor ~string(); // destructor void print(); void copy(char *); }; void string::print() { cout << s << endl; }