Presentation is loading. Please wait.

Presentation is loading. Please wait.

Constructors & Destructors

Similar presentations


Presentation on theme: "Constructors & Destructors"— Presentation transcript:

1 Constructors & Destructors

2 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

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

4 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).

5 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.

6 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.

7 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

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

9 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";

10 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();

11 Multiple Constructors in a class

12 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();

13 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).

14 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.

15 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&);

16 #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; }

17 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???

18 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 ?

19 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 *); };

20 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.

21 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

22 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

23 # 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); };

24 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); };

25 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(); }

26 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; }

27 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 };

28 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; }

29 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

30 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;

31 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.

32 #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; }


Download ppt "Constructors & Destructors"

Similar presentations


Ads by Google