Constructors
Constructors
Constructors
1
Constructor Function
A Constructor is a special member function
whose task is to initialize the object of its
class. Its name is same as 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.
2
class integer
{
int m, n;
public:
integer(); //constructor declared
};
integer::integer() //constructor defined
{
m=0;n=0;
}
3
• when a class contains constructor, object of
class is
initialized automatically.
class integer
{ int m,n;
public:
integer( ); // default constructor declared
};
6
Simple Program
// default constructor
#include<iostream.h>
class integer
{
int m,n;
public:
Integer(); // constructor declared
};
integer :: integer( ) // constructor defined
{
m= 0;
n=0;
}
7
Parameterized Constructors
• The constructor that can take arguments is called
parameterized constructor.
Class integer
{
Int m, n;
Public :
Integer (int x, int y); // parameterized constructor
};
Integer::integer(int x,int y)
{
m=x;
n=y;
}
8
• When a constructor is parameterized,
integer int1;
may not work.
• We must pass the initial values as
arguments to constructor fn when object is
created.
• By calling constructor explicitly
• By calling constructor implicitly
9
• integer int1 = integer(0,100);
//explicitly called
• Shorthand method.
10
# include<iostream.h> Int main()
Class integer {
{ Integer int1(0,100); //implicit
Int m,n; call
Public: Integer
Integer(int,int) int2=integer(10,20);
Void display() //explicit call
{ Int1.display();
Cout<<m; Int2.display();
Cout<<n; Return 0;
}}; }
Integer::integer(int x,int y)
{m=x; n=y;
}
11
Constructor function can also be defined as inline
function
• Constructor function can be defined using inline.
Class integer
{
int m,n;
public:
integer(int x,int y) //inline constructor
{
m=x; y=n;
}
};
12
Parameters of a constructor can be of any type except that
of class to which it belongs
class A
{
………………
………………
public:
A(A); // is illegal
};
13
Constructor can accept a
reference to its own class as a
parameter.
class A
{
……………..
………………
public:
A(A &i); //known as copy constructor
};
14
Multiple Constructors in a class
integer(); //No arguments
integer(int , int); // Two arguments
18
Constructors with default
arguments
complex(float real, float imag=0);
//The default value for argument imag is zero.
19
Distinguish between default constructor and default argument
constructor
21
Copy Constructor Example with Program
//fibonacci series using copy constructor
Void increment ( )
#include<iostream.h>
{
Class fibonacci { f0=f1;
Private : f1=fib;
int f0,f1,fib; fib=f0+f1;
Public : }
Void display ( )
Fiboancci () // constructor
{
{ Cout<<fib<<‘/t’;
f0=0; }
f1=1; };
fib=f0+f1; Void main( )
} {
Fibonacci number ;
Fibonacci (fibonacci &ptr) // copy construtor
Fibonacci num(&number);
//CC takes reference to an object of same class For(int i=0;i<=15;++i)
as argument {
{ Number.display();
f0=ptr.f0; Num.display();
f1=ptr.f1; Number.increment();
Num.increment();
fib=prt.fib;
} 22
} }
#include<iostream> void display (void)
Using namespace std ; { cout<<id;
Class code // class name }
{ };
Int id; int main()
Public : {
Code() code A(100);//object A is created
// constructor name same as class namecode B(A); // copy const. called
{ } code C= A; // CC called again} code D; // D is created, not intilized
Code(int a ) // constructor again
{ D=A;
Id=a; cout<<“\n” id of A:=A.display();
} cout<<“\n” id of B:=B.display();
Code (code &x) // copy constuctor cout<<“\n” id of C:=C.display();
{ id=x.id; // copy in the value cout<<“\n” id of D:=D.display();
} return 0;
}
23
Dynamic Initialization Of Objects
• Class objects can be intialized dynamically
too.
• The initial value of an object may be provided
during run time.
Advantage of Dynamic Initialization
}
fixed_deposit(long int p , int y , float r=0.12);
fixed_deposit(long int p , int y , int r);
void display(void);
};
25
fixed_deposit :: fixed_deposit(long int p, int y , float r)
{
_____________;
}
fixed_deposit::fixed_deposit(long int p , int y , int r)
{ cout<<“Enter amnt,prd,intrst”;
} cin>>p>>y>>R;
void fixed_deposit::display(void)
fd1=fixed_deposit(p,y,R);
{
} cout<<“Enter amnt,prd,intrst”;
int main() cin>>p>>y>>r;
{ fd1=fixed_deposit(p,y,r);
fixed_deposit fd1,fd2,fd3;cout<<“Enter amt,prd,intrst”;
long int p; cin>>p>>y;
int y; fd3=fixed_deposit(p,y);
float r; fd1.deposit();
int R; fd2.deposit();
fd3.deposit(); 26
Dynamic Constructor(DC)
• DC can also be used to allocate memory
while creating objects.
• This will enable the system to allocate right
amount of memory for each object when the
objects are not of the same size.
Resulting in: --------------------
Allocation of memory to objects at the time of
their construction is known as dynamic
construction of objects.
new
Memory is allocated with the help of
operator.27
class String int main()
{ {
char *name; char *first=“Joseph”;
int length; String name1(first),s1,s2;
public: s1.display();
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;}
28
Destructors
• Just as a default constructor is called when a
class object is first instantiated, a default
destructor is called when the object is
destroyed
• A default destructor cleans up any resources
allocated to an object once the object is
destroyed
• The default destructor is sufficient for most
classes, except when you have allocated
memory on the heap
29
Destructors
• You create a destructor function using the
name of the class, the same as a
constructor
30
Syntax rules for writing a destructor
function :
• A destructor function name is the same as
that of the class it belongs except that the
first character of the name must be a tilde
( ~).
• It is declared with no return types ( not even
void) since it cannot even return a value.
• It cannot de declared static ,const or volatile.
• It takes no arguments and therefore cannot
be overloaded.
• It should have public access in the class
declaration.
• Can’t be overloaded or inherited.
31
Class employee
{
Private :
Char name[20];
Int ecode ;
Char address[30];
Public :
Employee ( ) // constructor
~ employee ( ) // destructor
Void getdata( );
Void display( );
};
32
#include<iostream>
#include<stdio>
Class account {
Private :
Float balance;
Float rate;
Public:
Account( ); // constructor name
~ account ( );// destructor name
Void deposit( );
Void withdraw( );
Void compound( );
Void getbalance( );
Void menu( );
}; //end of class definition
Account :: account( ) // constructor
{
Cout<<“enter the initial balance\n”;
Cin>>balance;
}
33
Account :: ~account( ) // destructor
{
Cout<<“data base has been deleted\n”
}
// to deposit
Void account ::deposit( )
{
Float amount;
Cout<<“how much amount want to deposit”;
Cin>>amount;
Balance=balace+amount ;
}
34
#include<iostream>
Using namespace std;
Int count =0;
Class alpha
{
Public :
Alpha()
{
Count ++;
Cout <<“\n No. of object created “<<count;
}
~alpha()
{
35
Cout<<“\n No. of object destroyed “<<count;
Count --;
}
};
Int main()
{ cout<<“\n \n Enter main\n”;
Alpha A1 A2 A3 A4;
{
Cout<<“\n\n Enter block 1\n”;
Alpha A5;
}
{ cout<<“\n\n Enter Block 2 \n”;
Alpha A6;
}
36
Cout<<“\n \n RE-enter Main\n”;
Return 0; Enter Block 2
No. of object created :5
} Re-Enter Main No. of object destroyed
Output : Enter Main 4,3,2,1
No. of object created 1
No. of object created 2
No. of object created 3
No. of object created 4
Enter Block 1
No. ofobject created 5
No. of object Destroyed 5
37
Static Class Members
• You can use the static keyword when declaring class
members
• Static class members are somewhat different from static
variables
• When you declare a class member to be static, only one
copy of that class member is created during a program’s
execution, regardless of how many objects of the class you
instantiate.
41
Int item :: count;
Int main( )
{
Item a,b,c; //count is intialized to zero
a.getcount( ); // display count
b.getcount( );
c.getcount();
A B C
In this count data member is static variable within the
class and a,b,c are objects. Because there is only one
copy of count shared by all the three objects.
44
• We can initialize the static variable
• Int item : : count =10;
45
Static Member Functions
Like static member variable, we can also have static member functions. A
member function that is declared static has following prosperities.
A static function can have access to only other static members
(functions or variables) declared in the same class.
A static member function can be called using the class name( instead
of its objects) as below :-
Class name :: function-name;
//Static member functions :
#include<iostream>
Using namespace std;
Class test
{ int code;
Static int count; // static member variable
Public:
Void setcode( )
{
Code=++count;
}
Void showcode()
{
Cout<<“object number :”<<code<<“\n”;
}
Static void showcount() // static member function
{ cout<<“count:”<<count<<“\n”;
}
};
47
Int test : : count ;
Int main()
{
Test t1,t2;
T1.setcode();
T2.setcode();
Test::showcount() ; // accessing static function
Test t3;
T3.setcode();
Test:: showcount( );
T1.showcode();
T2.showcode();
T3.showcode();
Return 0;
}
48
• Important note :
The statement
Code=++count is executed whenever setcode() function is
invoked and the current value of count is assigned to
code. Since each object has its own copy of the code ,
the value contained in code represent a unique of its
object.
Remember that
Static void showcount ()
{
Cout <<code ; // code is not static
}
will not work.
49