Constructor,destructors cpp

Post on 20-May-2015

155 views 4 download

Tags:

Transcript of Constructor,destructors cpp

ObjectivesIn this chapter you will learn:About default constructorsHow to create parameterized constructorsHow to work with initialization listsHow to create copy constructors

1

Advanced ConstructorsConstructors can do more than

initialize data members

They can execute member functions and perform other types of initialization routines that a class may require when it first starts

2

Default ConstructorsThe 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

3

Constructor Function

4

A Constructor is a special member function whose task is to initialize the object of its class. It is special because it 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.

Default ConstructorsThe constructor function in Figure is an

example of a default constructorIn addition to initializing data members

and executing member functions, default constructors perform various types of behind-the-scenes class maintenance

5

Simple Program

6

// default constructor#include<iostream>Using namespace std;Class integer{Int m,n;Public: Integer(void); // constructor declared Void getinfo( );};Integer :: integer void( ) // constructor defined

{m= 0;n=0;}

Parameterized ConstructorsThe constructor integer( ) define above

initialize the data members of all the objects to zero. However is practice it may be necessary to initialize the various data elements of different objects with different values, when they are created.

A parameterized constructor allows a client to pass initialization values to your class during object instantiation

Instead of assigning default values, you can allow a client to pass in the value for these data members by designing the constructor function with parameters.

7

8

Class integer {Int m, n;Public : Integer (int x, int y);};Integer :: integer(int x,int y){m= x;n=y;}

By Calling the Constructor explicitly By Calling the consructor implicitly

integer int1 = integer(0,100);Explicitly called

Integer int1(0,100)Implicitly called.

Shorthand method.

9

Copy ConstructorThere will be times when you want to

instantiate a new object based on an existing object

C++ uses a copy constructor to exactly copy each of the first object’s data members into the second object’s data members in an operation known as member wise copying

A copy constructor is a special constructor that is called when a new object is instantiated from an old object

10

Copy ConstructorThe syntax for a copy constructor declaration is

class_name :: class_name (class_name &ptr)The Copy Constructor may be used in the following

format also using a const keyword. class_name :: class_name (const class_name &

ptr)Copy Constructor are always used when the compiler

has to create a temporary object of a class object.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.

11

Copy Constructor Example with Program

//fibonacci series using copy constructor

#include<iostream>

Using namespaces std ;Class fibonacci {Private : Unsigned long int f0,f1,fib;Public :Fiboancci () // constructor {F0=0;F1=1;Fib=f0+f1;}Fibonacci (fibonacci &ptr) // copy construtor{F0=ptr.f0;F1=ptr.f1;Fib=prt.fib;}

12

Void increment ( ){F0=f1;F1=fib;Fib=f0+f1;}Void display ( ){Cout<<fib<<‘/t’;}};Void main( ){Fibonacci number ;For(int i=0;i<=15;++i){Number.display();Number.increment();}}

#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 name code B(A); // copy const.

called{ code C= A; // CC called again} code D; // D is created, not

intilizedCode(int a ) { // constructor again D=A; // C C not called 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;

} 13

DestructorsJust 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

14

DestructorsYou 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

15

Syntax rules for writing a dectructor 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.

16

Class employee { Private :Char name[20];Int ecode ;Char address[30];Public :Employee ( ); // constructor ~ Employee ( ); // destructorVoid getdata( );Void display( );};

17

18

#include<iostream>#include<stdio>Class account {Private : Float balance;Float rate;Public: Account( ); // constructor name~ account ( );// destructor nameVoid deposit( );Void withdraw( );Void compound( );Void getbalance( );Void menu( );}; //end of class definition Account :: account( ) // constructor{Cout<<“enter the initial balance\n”;Cin>>balance;}Account :: ~account( ) // destructor

19

{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

#include<iostream>Using namespace std;Int count =0;Class alpha{Public : Alpha(){Count ++;Cout <<“\n No. of object created “<<count;}~alpha(){

20

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

21

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,1No. of object created 1No. of object created 2No. of object created 3No. of object created 4Enter Block 1No. ofobject created 5No. of object Destroyed 5

22

Static Class MembersYou can use the static keyword when

declaring class membersStatic class members are somewhat different

from static variablesWhen 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

Figure 7-38 illustrates the concept of the static and non-static data members with the Payroll class

23

Multiple Class Objects with Static and Non-Static Data Members

24

Static Data MembersYou declare a static data member in your

implementation file using the syntax static typename;, similar to the way you define a static variable

static data members are bound by access specifiers, the same as non-static data members

This means that public static data members are accessible by anyone, whereas private static data members are available only to other functions in the class or to friend functions

25

Static Data MembersYou could use a statement in the class

constructor, although doing so will reset a static variable’s value to its initial value each time a new object of the class is instantiated

Instead, to assign an initial value to a static data member, you add a global statement to the implementation file using the syntax type class::variable=value;

Initializing a static data member at the global level ensures that it is only initialized when a program first executes—not each time you instantiate a new object

26

Static Data MembersFigure 7-39 contains an example of the Stocks class, with the iStockCount static data member

Statements in the constructor and destructor increment and decrement the iStockCount variable each time a new Stocks object is created or destroyed

Figure 7-40 shows the program’s output

27

Static Data MembersYou can refer to a static data member by appending

its name and the member selection operator to any instantiated object of the same class, using syntax such as stockPick.iStockCount

By using the class name and the scope resolution operator instead of any instantiated object of the class, you clearly identify the data member as static

Figure 7-41 in the text shows an example of the Stocks class program with the dPortfolioValue static data member

The dPortfolioValue static data member is assigned an initial value of 0 (zero) in the implementation file

28

Static Data Members

To add to the Estimator class a static data member that stores the combined total of each customer’s estimate, follow the instructions listed on pages 403 and 404 of the textbook

29

Static Member FunctionsStatic member functions are useful for

accessing static data membersLike static data members, they can be

accessed independently of any individual class objects

This is useful when you need to retrieve the contents of a static data member that is declared as private

Static member functions are somewhat limited because they can only access other static class members or functions and variables located outside of the class

30

Static Member FunctionsYou declare a static member function similar

to the way you declare a static data member-- by preceding the function declaration in the interface file with the static keyword

You do not include the static keyword in the function definition in the implementation file

Like static data members, you need to call a static member function’s name only from inside another member function of the same class

31

Static Member FunctionsYou can execute static member functions

even if no object of a class is instantiatedOne use of static member functions is to

access private static data membersTo add to the Estimator class a static

member function that returns the value of the static lCombinedCost data member, use the steps on pages 405 and 406 of the textbook

32

Constant ObjectsIf you have any type of variable in a

program that does not change, you should always use the const keyword to declare the variable as a constant

Constants are an important aspect of good programming technique because they prevent clients (or you) from modifying data that should not change

Because objects are also variables, they too can be declared as constants

33

Constant ObjectsAs with other types of data, you only declare

an object as constant if it does not changeConstant data members in a class cannot be

assigned values using a standard assignment statement within the body of a member function

You must use an initialization list to assign initial values to these types of data members

There is an example of this code shown on page 407 of the textbook

34

Constant ObjectsAnother good programming technique is to

always use the const keyword to declare get functions that do not modify data members as constant functions

The const keyword makes your programs more reliable by ensuring that functions that are not supposed to modify data cannot modify data

To define the Estimator class’s get functions as constant, perform the procedures listed on page 408 of the textbook

35

SummaryThe default constructor is the constructor

that does not include any parameters and that is called for any declared objects of its class to which you do not pass arguments

Initialization lists, or member initialization lists, are another way of assigning initial values to a class’s data members

A copy constructor is a special constructor that is called when a new object is instantiated from an old object

36

SummaryOperator overloading refers to the creation of

multiple versions of C++ operators that perform special tasks required by the class in which an overloaded operator function is defined

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

37