Constructors

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 49

Default Constructors

• The default constructor does not include


parameters, and is called for any declared
objects of its class to which you do not
pass arguments
• Remember that you define and declare
constructor functions the same way you
define other functions, although you do not
include a return type because constructor
functions do not return values

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.

integer int1; //object int1 created

• Not only creates object int1 but also initializes


its data members m and n to zero.
• There is no need to write any statement to
invoke constructor function( as we do with
normal member functions)
4
Characteristics:
• They should be declared in public section.
• They are invoked automatically when objects
are created.
• They do not have return types, not even void
and therefore cannot return values.
• Like other C++ functions, they can have
default arguments.
• Constructors cannot be virtual
• We cannot refer to their addresses
• They cannot be inherited, though a derived
class can call the base class constructor
5
Default Constructors
• A constructor that accepts no parameter is
called default constructor.
• The default constructor for class a is A::A().
• If no such constructor is defined, then compiler
supplies a default constructor. A statement A a;
invokes default constructor

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

• integer int1(0,100) //implicitly


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

In the first case ___________________________


In the second case
_________________________

C++ permits us to use both these constructors


in the same class.
15
Multiple constructors in a class
Class integer
{ int m,n;
public:
integer() { m=0; n=0; } //consructor 1
integer(int a,int b) { m=a;n=b; } //constructor 2
integer(integer &i) { m=i.m; n=i.n; } //constructor 3
};
Statement
integer I1; //automatically invoke the 1st constructor
integer I2(10,20); //call the 2nd constructor
integer I3(I2); // wud invoke 3rd constructor which
copies the value of I2 into I3 16
COPY CONSTRUCTOR
• A copy constructor is used to declare and
initialize object of another class.
• Integer I3(I2); would define object I3 and
at the same time would initialize it to value
of I2.
• Another form :
• Integer I3=I2;
• Process of initializing through copy
constructor is known as copy initialization
17
When we say that constructor is
overloaded?

When more than one constructor function is


defined in a class,we say that constructor is
overloaded.

18
Constructors with default
arguments
complex(float real, float imag=0);
//The default value for argument imag is zero.

complex(5.0); //assigns 5.0 to real

complex C(2.0,5.0); //assigns 2.0 to real and


5.0 to imag

19
Distinguish between default constructor and default argument
constructor

A::A(int =0) //default constructor can be


called with either one argument or no
arguments.

When called with no arguments ,it becomes a


default constructor.

When both these forms are used in a class ,it


causes ambiguity for a statement such as
A a; // whether to call A::A() or A::A(int=0) 020
Copy Constructor
Copy Constructor are always used when
the compiler has to create a temporary
object of a class .The copy constructor are
used in the following situations:-
The Initialization of an object by another
object of the same class.
Return of object as a function value.
Stating the object as by value parameters
of a function.

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

1.We can provide various initialization formats,


using overloaded constructor
2.Provides the flexibility of using different
format of data at run time depending upon
the situation
24
class fixed_deposit
{
long int p_amount;
int years;
float rate;
float r_value;
public:
fixed_deposit()
{

}
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

• A destructor is commonly called in two


ways:
– When a stack object loses scope because the function in
which it is declared ends

– When a heap object is destroyed with the delete operator

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

// the program is not complete , the purpose is to clear the function


of constructor and destructor

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.

Static members can be of any one of the groups : public ,


private and protected ,but not a global data.
 It is initialized to zero when the first object is created. No
other initialization is permitted.
 Only one copy of that member is created for the entire
class and shared by all the objects of the class, no matter
how many object are created.
 It is visible only within the class, but lifetime is entire the
program.
The general syntax of the static data member is :-
Class user_defined_name
{
Private :
Static data_type variables ;
Static data_type variables ;
Public :
---};
39
A static data member of a class has the following properties

1. The access rule of the data member of a class is same for


the static data member also.
example : if a static member is declared as a private category
of a class, then non member functions cannot access these
members. If a static member is declared as public, then any
member of the class can access.
2. Whenever a static data member is declared and it has only
a single copy , it will be shared by all the instance of class.
That is, the static member becomes global instances of the
class.
3. The static data member should be created and initialized
before main() function control block begins
#include<iostream>
Using namespace std;
Class item
{
Static int count;
Int number;
Public :
Void getdata(int a)
{
Number=a;
Count++;
}
Void getcount(void)
{
Cout<<“count:”<<count<<\n”;
}
};

41
Int item :: count;
Int main( )
{
Item a,b,c; //count is intialized to zero
a.getcount( ); // display count
b.getcount( );
c.getcount();

a.getdata(100); // getting data into objects a,b,c


b.getdata(200);
c.getdata(300);
Cout<<“After reading data “<<“\n”;
a.getcount(); b.getcount();c.getcount(); // display count
Return 0;
} 42
• IMPORTANT POINTS :
The Type and scope of each static member
variable must be defined outside the class
defination.
Int item :: count; // definition of static data
member
This is necessary because the static data
members are stored separately rather than as
apart of an object. Since they are associated
with class itself rather than with any class
object, they are also known as class variables.
The static variable count is initialized to zero
when the object are created. The count is
incremented whenever the data is read into an
object.
43
Count
Initial count 0,1,2,3

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

You might also like