Você está na página 1de 34

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 integer { int n, m; public: integer(void); .. .. };

integer : : integer(void) { m=0; n=0; }

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 cant return values. They cant be inherited through a derived class. They can have default arguments. Constructors cannot be virtual. We cannot refer to their addresses.

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

when a new instance is created.

Comments on constructors (cont.)


void main() { rectangle rc(3.0, 2.0);
rc.posn(100, 100); rc.draw(); rc.move(50, 50); rc.draw(); }

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

Multiple Constructors in a class

class rectangle { private: float height; float width; int xpos; int ypos; public: rectangle() { xpos = 0; ypos = 0; } rectangle(float, float); // constructor void draw(); // draw member function void posn(int, int); // position member function void move(int, int); // move member function }; rectangle::rectangle(float h, float w) { height = h; width = w; }

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 A copy constructor has the following


object using another object of the same class. general function prototype: class_name (const class_name&);

class rectangle { private: float height; float width; int xpos; int ypos; public: rectangle(float, float); // constructor rectangle(const rectangle&); // copy constructor void draw(); // draw member function void posn(int, int); // position member function void move(int, int); // move member function };

rectangle::rectangle(const rectangle& old_rc) { height = old_rc.height; width = old_rc.width; xpos = old_rc.xpos; ypos = old_rc.ypos; }

void main() { rectangle rc1(3.0, 2.0); rectangle rc2(rc1); rectangle rc3 = rc1;
C++ statements; }

// use constructor // use copy constructor // alternative syntax for // copy constructor

#include<iostream.h> Class code { int id; Public: code() { } code(int a) { id = a; } code (code & x) { id = x. id; } void display(void) { 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 Default copy constructors work fine unless
the class contains pointer data members ... why???
C++ compiler builds a default copy constructor for each class which is doing a memberwise copy between objects.

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

str2.copy("Mary");
str1.print(); str2.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; s = new char[size+1]; strcpy(s,old_str.s);


}

void main()
{

string str1("George"); string str2 = str1;

str1.print(); str2.print();

// what is printed ?

str2.copy("Mary"); str1.print(); // what is printed now ? str2.print();


}

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.h> # include <string.h> class str { char *name; int len; public: str() { len=0; name=newchar[len+1]; } str(char *s) { len=strlen(s); name=newchar[len+1]; 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.len; delete new; name=newchar[len+1]; strcpy(name,a.name); strcat(name,b.name); };

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

Static Constructors
A static constructor is used to initialize any

static data members. It is called automatically


before the first instance is created or any

static members are referenced. A static


constructor does not take access modifiers or

have parameters and therefore cannot be


called using the new keyword.

Properties of Static Constructors

A static constructor does not take access

modifiers or have parameters. Accessibility defaults to the same accessibility as the class itself. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. A static constructor cannot be called directly. A static constructor cannot be overloaded. A static constructor is not inheritable.

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 *); // 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 When a class contains a pointer to memory
you allocate, it is your responsibility to release the memory before the class instance is destroyed. compiler generates a default destructor for you.

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

Você também pode gostar