Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt Constructors...

Post on 13-Jan-2016

215 views 0 download

Transcript of Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt Constructors...

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Constructors andDestructors

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Constructors

• 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 name.

• The constructor is invoked whenever an object of its associated class is created.

• It is called constructor because it constructs the values of data members of the class.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Constructor - example

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.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Constructors

• 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 …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• If no such constructor is defined , then the compiler supplies a default constructor , therfore a stmt such as

• A a;

Invokes the default constructor of the compiler to create the object a.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Characteristics of Constructors

• They should be declared in the public section.

• They are invoked automatically when the objects are created.

• They do not have return types, not even void and they cannot return values.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Characteristics of Constructors

• They cannot be inherited, though a derived class can call the base class constructor.

• Like other C++ functions, Constructors can have default arguments.

• Constructors can not be virtual.

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Characteristics of Constructors

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

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Constructors

• When a constructor is declared for a class initialization of the class objects becomes mandatory.

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Types of constructors

1. Default constructor

2. Parameterized constructor

3. Copy constructor

4. Dynamic constructor

5. Explicit constructor

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Default constructor

• This is the simplest way of defining the constructor. We simply define the constructor without passing any arguments to it.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Default constructor• #include<iostream.h>

• #include<conio.h>

• class image

• {

• int height, width;

• public:

• image()

• { height=0,width=0;}

• int area()

• {

• cout<<"enter the value of height"<<"\n";

• cin>>height;

• cout<<"enter the value of width"<<"\n";

• cin>>width;

• return(height * width);

• }

• };

• void main()

• {

• image obj1;

• clrscr();

• cout<<"the area is :"<<obj1.area()<<endl;

• getch();

• }

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Parameterized Constructors

• It may be necessary to initialize the various data elements of different objects with different values when they are created.

• This is achieved by passing arguments to the constructor function when the objects are created.

• The constructors that can take arguments are called parameterized constructors.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• Explicit means clearly expressed or readily observable. Implicitmeans implied or expressed indirectly.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Call mechanism

• We can call parameterized constrcutor using

• 1. implicit call

• 2. explicit call

image obj1(5,3) //implicit call

image obj1=image(5,3) //explicit call

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Parameterized Constructors

class add{ int m, n ; public : add (int, int) ; ------};add : : add (int x, int y){ m = x; n = y;}

• 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

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Parameterized Constructors

• #include<iostream.h> class integer{ int m,n; public: integer(int, int); void display(); { cout<<“m=“<<m<<“\n”; cout<<“n=“<<n<<“\n”; }};

integer ::integer(int x,int y)

{ m = x; n = y;}

void main()

{

Integer int1(0,100); //implicit call

Integer int2=integer(25, 75) //explicit call

cout<<“\n OBJECT”<<“\n”;

int1.display();

cout<<“\n object2”<<“\n”;

int2.display();

}

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• The constructor function can also be defined as inline function.

• Class integer

• {

• int m, n;

• public:

• integer( int x, int y) //inline constructor

• {

• m=x; y=n;

• }

• };

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• The parameter of a constructor can be of any type except that of the class to which it belongs,

• class A

• {

• ……

• …….

• public:

• A(A);

• };

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• However a constructor can accept a reference to its own class as a parameter.

• class A

• {

• ………..

• …………..

• public:

• A(A&);

• };

• this is called copy constrcutor.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Multiple Constructors in a Class

• C + + permits to use more than one constructors in a single class.

• Add( ) ; // No arguments

• Add (int, int) ; // Two arguments

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Multiple Constructors in a Class

class add{ int m, n ; public : add ( ) {m = 0 ; n = 0 ;} add (int a, int b) {m = a ; n = b ;} add (add & i) {m = i.m ; n = i.n ;}};

• The first constructor receives no arguments.

• The second constructor receives two integer arguments.

• The third constructor receives one add object as an argument.

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Multiple Constructors in a Class

class add{ int m, n ; public : add ( ) {m = 0 ; n = 0 ;} add (int a, int b) {m = a ; n = b ;} add (add & i) {m = i.m ; n = i.n ;}};

• Add a1; – Would automatically invoke the

first constructor and set both m and n of a1 to zero.

• Add a2(10,20);– Would call the second

constructor which will initialize the data members m and n of a2 to 10 and 20 respectively.

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Multiple Constructors in a Class

class add{ int m, n ; public : add ( ) {m = 0 ; n = 0 ;} add (int a, int b) {m = a ; n = b ;} add (add & i) {m = i.m ; n = i.n ;}};

• Add a3(a2);– Would invoke the third

constructor which copies the values of a2 into a3.

– This type of constructor is called the “copy constructor”.

• Construction Overloading– More than one constructor

function is defined in a class.

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Multiple Constructors in a Class

class complex{ float x, y ; public : complex ( ) { } complex (float a) { x = y = a ; } complex (float r, float i) { x = r ; y = i } ------};

• complex ( ) { }

– This contains the empty body and does not do anything.

– This is used to create objects without any initial values.

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Multiple Constructors in a Class

• C + + compiler has an implicit (Default) constructor which creates objects, even though it was not defined in the class.

• This works well as long as we do not use any other constructor in the class.

• However, once we define a constructor, we must also define the “do-nothing” implicit constructor.

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• #include<iostream.h>

• class complex

• {

• float x,y;

• public:

• complex()

• { }

• complex(float a) {x=y=a;}

• complex(float real,float imag)

• {x=real;y=imag;}

• friend complex sum(complex, complex);

• friend void show(complex);

• };

• complex sum(complex c1, complex c2)• {

• complex c3;• c3.x = c1.x + c2.x;• c3.y = c1.y + c2.y;• return(c3);

• }

• void show(complex c)• {•

cout<<c.x<<"+j"<<c.y<<"\n";

• }

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• int main()

• {

• complex A(2.7, 3.5);

• complex B(1.6);

• complex C;

• C= sum(A,B);

• cout<<"A = "; show(A);

• cout<<"B= ";show(B);

• cout<<"C= ";show(C);

• return 0;

• }

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• There are three constructors in the class complex. The first constructors, which takes no arguments, is used to create objects which are not initialized;

• The second which takes one argument, is used to create objects and initialize them.

• The third ,which take two arguments is also used to create objects and initialize them to specific values.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Constructors with Default Arguments

• It is possible to define constructors with default arguments.

• Consider complex (float real, float imag = 0);– The default value of the argument imag is zero.– complex C1 (5.0) assigns the value 5.0 to the real

variable and 0.0 to imag.– complex C2(2.0,3.0) assigns the value 2.0 to real and

3.0 to imag.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Constructors with Default Arguments

• A : : A ( ) Default constructor

• A : : A (int = 0) Default argument constructor

• The default argument constructor can be called with either one argument or no arguments.

• When called with no arguments, it becomes a default constructor.

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Copy Constructor

•A copy constructor is used to declare and initialize an object from another object.

integer (integer & i) ;

integer I 2 ( I 1 ) ; or integer I 2 = I 1 ;

The process of initializing through a copy constructor is known as copy initialization.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Copy Constructor

The statement

I 2 = I 1;

will not invoke the copy constructor.

If I 1 and I 2 are objects, this statement is legal and assigns the values of I 1 to I 2, member-by-member.

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Copy Constructor

• A reference variable has been used as an argument to the copy constructor.

• We cannot pass the argument by value to a copy constructor.

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• #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); // object a is created and initialized

code B(A); // copy constructor called

code C=A; //copy constructor called again

code D; // D is created , not initialized D=A; //copy constructor not called

cout<<"\n id of A :"; A.display();

cout<<"\n id of B:" ; B.display();

cout<<"\n id of C:"; C.display();

cout<<"\n id of D:"; D.display();

• return 0;

• }

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Explicit constructer

• The constructor which takes one argument is by default an implicit converter constructor.

• This is called implicit converter because it converts its arguments to an object of its class.

• Since the conversion is automatic, we need not apply any casting.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• In case we do not want such automatic conversion to take place, we may do so by declaring the one argument constructor as explicit.

• We can avoid such implicit conversion by placing the keyword explicit for the constructor.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• #include < iostream.h>• class ABC• {• int m;• public :• explicit ABC(int i)• {• m= I;• }• //………………..• //……………………..• };•

• Hence the objects of ABC can be created using only the following form:

• ABC abc1(100);• The automatic conversion

form• ABC abc1 =100;• Is not allowed and illegal.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Dynamic Constructors

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

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Dynamic Constructors

• Allocation of memory to objects at the time of their construction is known as dynamic construction of objects.

• The memory is created with the help of the new operator.

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• class String //user-defined string type• {• private:• char* str; //pointer to string• public:• String(char* s) //constructor, one arg• {• int length = strlen(s); //length of string argument• str = new char[length+1]; //get memory• strcpy(str, s); //copy argument to it• }• ~String() //destructor• {• cout << “Deleting str.\n”;• delete[] str; //release memory• }• void display() //display the String• {• cout << str << endl;• }• };

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• int main()• { //uses 1-arg constructor• String s1 = “Who knows nothing doubts nothing.”;• cout << “s1=”; //display string• s1.display();• return 0;• }

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Dynamic constrcutors

• #include<iostream.h>

• #include<string.h>

• class string

• {

• char *name;

• int length;

• public:

• string()

• {

• length = 0;

• name = new char[length + 1];

• }

• string (char *s)

• {

• length = strlen(s);

• name = new char[length + 1];

• strcpy(name, s);

• }

• void display()

• {

• cout<<name<<"\n"; }

• void join( string &a,string &b);

• };

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• void string :: join(string &a, string &b)• {• length =a.length + b.length;• delete name;• name = new char[length+1];• strcpy(name, a.name);• strcat(name, b.name);• }• int main()

• {• char *first="joseph";• string name1(first),name2("louis"),name3("lagrange"),s1,s2;• s1.join(name1,name2);• s2.join(s1,name3);• name1.display();• name2.display();• name3.display();• s1.display();• s2.display();

• return 0;

• }

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Destructors

• A destructor is used to destroy the objects that have been created by a constructor.

• Like constructor, the destructor is a member function whose name is the same as the class name but is preceded by a tilde.

eg: ~ integer ( ) { }

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Destructors

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

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Destructors

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

continue …

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• There is only one destructor in a class and hence cannot be overloaded.

• Destrcutors can be used to deallocate memory for an object.

• If you don’t explicitely provide a destrcutor of your own then a compiler generates a default destructor for you.

• It cannot be declared static or const.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• Unlike constructor, destructor can be virtual.

• Programmer cannot access the address of the destrcutor.

• An object with a destructor cannot be used as a memner of a union.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Const member function

• void display() const;

• double getsalary() const;

• When a member function does not modify any data member of its class and simply access it then such a member function are declared as const.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Initializer list

• C++ provides an alternative syntax for intilaizing data members of the object in the constrcutor known as initializer list. A rectangle constrcutor with two parameters can be rewritten to use the initializer list is as follows

• rectangle( int a , int b): length (a), breadth (b) { ………..}

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• Up until now, we’ve been initializing our class member data in the constructor using the assignment operator. For example:

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• class Something• {• private:•     int m_nValue;•     double m_dValue;•     int *m_pnValue;•  • public:•     Something()•     {•         m_nValue = 0;•         m_dValue = 0.0;•         m_pnValue = 0;•     }• };

• When the class’s constructor is executed, m_nValue, m_dValue, and m_chValue are created. Then the body of the constructor is run, where the member data variables are assigned values.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• So far, the classes that we have written have only included non-const or pointer member variables. However, what happens when we want to use const or reference variables as member variables? As you have learned in previous lessons, const and reference variables must be initialized on the line they are declared

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• class Something

• {

• private:

•     const int m_nValue;

• public:

•     Something()

•     {

•         m_nValue = 5;

•     }

• };

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• This produces code similar to the following:

• const int nValue; // error, const vars must be //assigned values

immediately

• nValue = 5;

• Consequently, assigning const or reference member variables values in the body of the constructor is not sufficient.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Initialization lists• C++ provides another way of initializing member variables

that allows us to initialize member variables when they are created rather than afterwards. This is done through use of an initialization list.

• In the lesson on basic addressing and variable declaration, you learned that you could assign values to variables in two ways: explicitly and implicitly:

• 1• 2• .

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• int nValue = 5; // explicit assignment

• double dValue(4.7); // implicit assignment

• Using an initialization list is very similar to doing implicit assignments

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

explicit assignments in the constructor body:

• class Something

• {

• private:

• int m_nValue;

• double m_dValue;

• int *m_pnValue;

• public:

• Something()

• {

• m_nValue = 0;

• m_dValue = 0.0;

• m_pnValue = 0;

• }

• };

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Now let’s write the same code using an initialization list:

• class Something

• {

• private:

•     int m_nValue;

•     double m_dValue;

•     int *m_pnValue;

•  

• public:

•     Something() : m_nValue(0), m_dValue(0.0), m_pnValue(0)

•     {

•     }

• };

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

• The initialization list is inserted after the constructor parameters, begins with a colon (:), and then lists each variable to initialize along with the value for that variable separated by a comma. Note that we no longer need to do the explicit assignments in the constructor body, since the initialization list replaces that functionality. Also note that the initialization list does not end in a semicolon.

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Here’s an example of a class that has a const member variable:

• class Something

• {

• private:

•     const int m_nValue;

• public:

•     Something(): m_nValue(5)

•     {

•     }

• };

Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt

Thank You