You are on page 1of 47

Unit -II

Contents
• Constructors
• Parameterized constructors
• Constructor overloading.
• Copy constructor,
• Destructors,
• Default arguments
• Dynamic memory allocation- new, delete operators
• This pointer
• Friend classes and Friend functions.
constructor
• A class constructor is a special member function of a class
that is executed whenever we create new objects of that
class.
• A constructor will have exact same name as the class

•  It does not have any return type at all


• Constructors can be very useful for setting initial values for
certain member variables
3
Constructor(cont..)
• The C++ runtime system makes sure that the constructor of a
class is the first member function to be executed
automatically when an object of the class is created.
• It is of course possible to define a class which has no
constructor at all;
• In such a case, the runtime system calls a dummy constructor
(i.e., which performs no action) when its object is created.
Constructor(cont..)
• Similar to other members, the constructor can be defined
either within or outside the body of a class.
• It can access any data member like all other member
functions but cannot be invoked explicitly and must have
public status to serve its purpose.
• The constructor which does not take arguments explicitly is
called a default constructor.
EXAMPLE
Line::Line() int main( )
class Line { {
{ cout << "Object is being created”; Line line;
public: }
void setLength( double len ); // set line length
double getLength( void ); void Line::setLength( double len ) line.setLength(6.0);
Line(); // This is the constructor { cout << line.getLength() <<endl;
length = len;
private: } return 0;
double length; }
}; double Line::getLength( void )
{
return length;
}

SRM University, John Blesswin 6


constructor
#include <iostream.h> cout << “here’s function func()” << endl;
class Test }
{ void main()
public: // ‘public’ function: {
Test(); // the constructor Test X; // local object in function main()
}; cout << “main() function” << endl;
Test::Test() // here is the definition func();
{ }
cout << “constructor of class Test called” <<
endl;
}
// and here is the test program:
constructor of class Test called (global object G)
Test G; // global object
constructor of class Test called (object X in main())
void func()
main() function
{
constructor of class Test called (object L in func())
Test L; // local object in function func()
here’s function func()
PARAMETERIZED CONSTRUCTORS
• Constructors with arguments are called
parameterized constructors.
void Line::setLength( double len )
class Line {
{ length = len;
public: }
void setLength( double len );
double getLength( void ); double Line::getLength( void )
Line(double len); // This is the constructor {
return length;
}
private:
double length; int main( )
}; {
Line line(10.0);
// get initially set length.
Line::Line( double len) cout << "Length of line : " << line.getLength()
{ <<endl;
cout << "Object is being created, length = " << len; // set line length again
length = len; line.setLength(6.0);
} cout << "Length of line : " << line.getLength()
<<endl;
return 0;
}
9
DESTRUCTOR
• When an object is no longer needed, it can be destroyed.

• A class can have another special member function called the

destructor, which is invoked when an object is destroyed.

• This function complements the operation performed by any of

the constructors, in the sense that it is invoked when an object

ceases to exist.

• Even when a program interrupted using an exit() call, the

destructors are called for all objects which exist at that time.
DESTRUCTOR
•Similar to constructors, a destructor must be declared in the public section of
a class so that it is accessible to all its users.
•Destructors have no return type.
•It is incorrect to even declare a void return type.
•A class cannot have more than one destructor
DESTRUCTOR
#include <iostream.h>
class Test
{
public: // ‘public’ function:
Test(); // the constructor
~Test(); // the destructor
};
Test::Test() // here is the definition of constructor
{
cout << “constructor of class Test called” << endl;
}
Test::~Test() // here is the definition of destructor
{
cout << “destructor of class Test called” << endl;
}
void main() Output:
{ constructor of class Test called
Test x; // constructor is called while creating terminating main()
cout << “terminating main()” << endl; destructor of class Test called
} // object x goes out of scope, destructor is called
CONSTRUCTOR OVERLOADING
• a class can have multiple constructors. This is
called constructor overloading.
• All the constructors have the same name as the
corresponding class, and they differ only in terms
of their signature.
• In terms of the number of arguments, or data
types of their arguments, or both
CONSTRUCTOR OVERLOADING

•If no arguments are passed - the no-argument constructor, AccClass().


•If only an int argument, is provided - the one-argument constructor
AccClass(int).
•If both an int as well as a float argument is provided -by invoking the two-
argument constructor, AccClass(int,float).
CONSTRUCTOR OVERLOADING
class Line
void Line::setLength( double len )
{
{
public: length = len;
void setLength( double len ); }
double getLength( void );
Line(double len); // This is the constructor1 double Line::getLength( void )
Line(double len, double wid); // This is the c2 {
private: return length;
double length,width; }
int main( )
}; {
Line::Line( double len) Line line(10.0);
{ Line line2(20.0,20.0);
cout << "Object is being created, length = " << len; // get initially set length.
length = len; cout << "Length of line : " << line2.getLength()
} <<endl;
Line::Line( double len, double wid) // set line length again
{ line.setLength(6.0);
cout << "Object is being created "; cout << "Length of line : " << line2.getLength()
length = len; width= wid; <<endl;
} return 0;
15
}
ORDER OF CONSTRUCTION AND DESTRUCTION
class Test Test g(“global”); // global object
{ void func()
private: {
char *name; Test L(“func”); // local object in function func()
public: // ‘public’ function: cout << “here’s function func()” << endl;
Test(); // the constructor }
Test(char *msg); // one-argument constructor void main()
~Test(); { object created most recently is
}; Test x(“main”); //the first
local one
object to be destroyed
in function main{)
Test::Test(char *NameIn) func();
{ cout << “main() function - termination” << endl;
strcpy( name, NameIn ); }
cout << “Test object “ << NameIn << “ created” << endl;
Output:
}
Test object global created
Test::~Test() Test object main created
{ Test object func created
cout <<“Test object “ << name << “ destroyed” << endl; here’s function func()
delete name; // release memory Test object func destroyed
} main()function - termination
Test object main destroyed
// and here is the test program:
Test object global destroyed
CONSTRUCTORS WITH DEFAULT ARGUMENTS
• In C++, constructors can also be defined with default arguments.
• If any arguments are passed during the creation of an object, the
compiler selects the suitable constructor with default arguments.
CONSTRUCTORS WITH DEFAULT ARGUMENTS (cont..)
#include<iostream> data3 is "<<data1<<", "<< data2<<" and "<<
using namespace std; data3<<endl;
}
class Simple{ int main(){
int data1; Simple s(12, 13);
int data2; s.printData();
int data3; return 0;
public: }
Simple(int a, int b=9, int c=8){
data1 = a;
Output:
data2 = b;
The value of data1, data2 and data3 is 12, 13 and 8
data3 = c;
}
void printData();
};
void Simple :: printData(){
cout<<"The value of data1, data2 and
CONSTRUCTORS WITH DEFAULT ARGUMENTS (cont..)
class X
{ if the default constructor is removed, the program works properly.
int value;
public:
X()
// Error: This leads to errors as compiler will not be able to
{
decide which constructor should be called
value=0;
}
X(int i=0)
{
value=i; ambiguity whether to call X:: x() or X:: X (int i= 0).
} };
int main()
{
X c;
X cl(4); // OK
return 0; }
copy constructor
• a constructor having a reference to an
instance of its own class as an argument is
known as a copy constructor.
copy constructor
#include <iostream>   };  
class A   int main()  
{   {  
   public:     A a1(20);  // Calling the parameterized c
    int x;   onstructor.  
    A(int a)   // parameterized constructor.    A a2(a1); //  Calling the copy constructor
    {   . cout<<a2.x;  
      x=a;     return 0;  
    }   }  
    A(A &i)               // copy constructor  
    {  
        x = i.x;  
    }  
In C++, a Copy Constructor may be called in
following cases:

• When we initialize the object with another existing object of the


same class type. For example, Student s1 = s2, where Student is
the class.
• When the object of the same class type is passed by value as an
argument.
• When the function returns the object of the same class type by
value.
this POINTER
• this is a pointer variable, which always contains the address
of the object.
• Every member function of a class is born with a pointer called
this, which points to the object with which the member
function is associated.
• The this pointer can also be used to access the data in the
object it points to.
this POINTER
this POINTER
#include <iostream>          void display()    
using namespace std;           {    
class Employee {               cout<<id<<"  "<<name<<"  "<<salary<<endl
   public:   ;    
    int id; //data member (also instance variable)               }    
   string name; // };  
data member(also instance variable)  float salary int main(void) {  
;       Employee e1 =Employee(101, "Sonoo", 890000); 
       Employee(int id, string name, float salary)     //creating an object of Employee   
        {         Employee e2=Employee(102, "Nakul", 59000); //
             this->id = id;     creating an object of Employee  
            this->name = name;         e1.display();    
            this->salary = salary;        e2.display();    
        }         return 0;  
}  
Memory allocation
• Reserving or providing space to a variable is called memory allocation.

• Static allocation or compile-time allocation - Static memory allocation

means providing space for the variable. The size and data type of the

variable is known, and it remains constant throughout the program.

• Dynamic allocation or run-time allocation - The allocation in which

memory is allocated dynamically. In this type of allocation, the exact

size of the variable is not known in advance. Pointers play a major role

in dynamic memory allocation.


Memory allocation
• In C++, memory is divided into two parts -
• Stack - All the variables that are declared inside any function
take memory from the stack.
• Heap - It is unused memory in the program that is generally
used for dynamic memory allocation.
Dynamic memory allocation using the new operator

• To allocate the space dynamically, the operator new is used.

• It means creating a request for memory allocation on the free store.

• If memory is available, memory is initialized, and the address of that space


is returned to a pointer variable.

Syntax int *m = new int


Pointer_variable = new data_type; int *m = new int(20);
float *d = new float(21.01);
• The pointer_varible is of pointer data_type.

• The data type can be int, float, string, char, etc.


Allocate a block of memory

• We can also use a new operator to allocate a block(array) of a particular


data type.

For example

int *arr = new int[10]


• returns a pointer to the first element of the array. Hence, arr[0] is the first
element and so on.
• normal arrays is deallocated by the compiler.

• Whereas the block is created dynamically until the programmer deletes it


or if the program terminates.
Delete operator
delete the allocated space in C++ using the delete operator.
Syntax
delete pointer_variable_name
Example
delete m; // free m that is a variable
delete [] arr; // Release a block of memory
#include <iostream> int *arr = new int[size];
using namespace std; for (int i = 0; i< size; i++)
int main () arr[i] = i+1;
{
// Pointer initialization to null cout<< "Value store in block of memory: ";
int* m = NULL; for (int i = 0; i< size; i++)
// Request memory for the variable cout<<arr[i] << " ";
// using new operator // freed the allocated memory
m = new int; delete m;
// Store value at allocated address delete f;
*m=29; // freed the block of allocated memory
cout<< "Value of m: " << *m <<endl; delete[] arr;
// Request block of memory return 0;
// using new operator }
float *f = new float(75.25);
cout<< "Value of f: " << *f <<endl;
// Request block of memory of size Value of m: 29
int size = 5;
Value of f: 75.25
Value store in block of memory: 1 2 3 4 5
Dynamic Allocation using Constructor
#include <iostream>
using namespace std;
class stud {
public:
stud()
Constructor Used
{ Constructor Used
cout << "Constructor Used" << endl; Constructor Used
} Constructor Used
~stud() Constructor Used
{ Constructor Used
cout << "Destructor Used" << endl; Destructor Used
} Destructor Used
};
Destructor Used
Destructor Used
int main()
{
Destructor Used
stud* S = new stud[6]; Destructor Used
delete[] S;
}
Two types of copies are produced by the
constructor:
• Shallow copy
• Deep copy

Shallow Copy
• The default copy constructor can only produce the shallow copy.

• A Shallow copy is defined as the process of creating the copy of


an object by copying data of all the member variables as it is.
Shallow copy of the constructor:
#include <iostream>       void showdata()  
  using namespace std;       {  
  class Demo           std::cout << "value of a is : " <<a<< std::endl;  
{           std::cout << "value of b is : " <<b<< std::endl;  
    int a;           std::cout << "value of *p is : " <<*p<< std::endl;  
    int b;       }  
    int *p;   };  
    public:   int main()  
    Demo()   {  
    {     Demo d1;  
        p=new int;     d1.setdata(4,5,7);  
    }     Demo d2 = d1;  
    void setdata(int x,int y,int z)     d2.showdata();  
    {       return 0;  
        a=x;   }  
        b=y;  
        *p=z;  
    }  
Shallow copy

Demo d2 = d1; 

•Thus, the pointer p of both the objects point to the same memory location.

•Therefore, when the memory of a field is freed, the memory of another field is

also automatically freed as both the fields point to the same memory location.
Deep copy
• Deep copy dynamically allocates the memory for the copy
and then copies the actual value, both the source and copy
have distinct memory locations.

• In this way, both the source and copy are distinct and will
not share the same memory location.

• Deep copy requires us to write the user-defined constructor.


Deep copy

•It creates the exact copy of the value types data and the
object pointed by the pointer p.
•Deep copy does not create the copy of a reference type
variable.
Deep copy
#include <iostream>       void setdata(int x,int y,int z)  
using namespace std;       {  
class Demo           a=x;  
{           b=y;  
    public:           *p=z;  
    int a;       }  
    int b;       void showdata()  
    int *p;       {  
     Demo()           std::cout << "value of a is : " <<a<< std::endl;  
    {           std::cout << "value of b is : " <<b<< std::endl;  
        p=new int;           std::cout << "value of *p is : " <<*p<< std::endl;  
    }       }  
    Demo(Demo &d)   };  
    {   int main()  
        a = d.a;   {  
        b = d.b;     Demo d1;  
        p = new int;     d1.setdata(4,5,7);  
        *p = *(d.p);     Demo d2 = d1;  
    }     d2.showdata();  
  return 0;  
}  
FRIEND FUNCTIONS AND FRIEND CLASSES

• One of the convenient and controversial features of C++ is


allowing nonmember functions to access even the private
members of a class using friend functions or friend classes.
• the functions of another class to access a different class’s private
members.
FRIEND FUNCTIONS AND FRIEND CLASSES
FRIEND FUNCTIONS AND FRIEND CLASSES

• The function declaration must be prefixed by the keyword friend


whereas the function definition must not.
• The function could be defined anywhere in the program similar to any
normal C++ function.
• The functions that are declared with the keyword friend are called
friend functions.
• A function can be a friend to multiple classes.
FRIEND FUNCTIONS AND FRIEND CLASSES
special characteristics:
• The scope of a friend function is not limited to the class in which it has
been declared as a friend.
• A friend function cannot be called using the object of that class; it is
not in the scope of the class.
• It can be invoked like a normal function without the use of any object.
• Unlike class-member functions, it cannot access the class members
directly.
• However, it can use the object and the dot operator with each member
name to access both the private and public members.
• It can be either declared in the private part or the public part of a class
without affecting its meaning.
FRIEND FUNCTIONS AND FRIEND CLASSES
#include<iostream> void decrement(A &a) {
using namespace std; a.value--; // Error:: not allowed to access
class A } private data
{ class B
private: { // class B: tries to access A’s
int value; // value is private data public: private data
public: void touch(A &a)
void setval( int v ) {
{ a.value++;
value = v; } };
} int main()
int getval () {
{ A a1; B b1;
return( value
friend);class B; // B is my friend, I trust a1.setval(5);
} him b1.touch(a1);
}; friend void decrement(A &what); // decrement(a1);
decrement () is also a good cout<<"value is ="<<a1.getval(); }
Bridging Classes with Friend Functions
#include <iostream.h> void setdata( int init )
class two; // advance declaration like function prototype {
class one data2 = init;
{ }
private: friend int add_both(one a, two b); // friend function
int datal; };
public: // friend function of class one and two
void setdata( int init ) int add_both(one a, two b)
{ {
datal = init; return a.datal + b.data2;
} }
friend int add_both( one a, two b }; // friend function void main()
}; {
class two one a;
{ two b;
private: a.setdata( 5 );
int data2; b.setdata( 10 );
public: cout << “Sum of one and two: “ << add_both(a, b);
}
Friend Classes
Friend Classes
#include <iostream.h> }
class girl; void setdata( int in )
class boy {
{ income = in;
private: // private members }
int incomel; void show()
int income2; {
public: boy bl;
void setdata( int inl, int in2 ) bl.setdata( 100, 200 );
{ cout << “boy’s Income! in show(): “ << bl.incomel << endl;
incomel = inl; cout << “girl’s income in show(): “ << income << endl;
income2 = in2; }
} };
friend class girl; // class girl can access private data void main()
}; {
class girl boy bl;
{ girl gl;’
int income; // income is private data member bl.setdata( 500, 1000 );
public: gl.setdata( 300 );
int girlfunc( boy bl ) cout << “boy bl total income: “ << gl.girlfunc(bl) << endl;
{ gl.show();
return bl.incomel+bl.income2; };
Class Friend to a Specified Class Member
• When only a specific member function of one class should be a friend function
of another class, it must be specified explicitly using the scope resolution
operator.

You might also like