Upload
govind-upadhyay
View
228
Download
0
Embed Size (px)
Citation preview
7/29/2019 Objected Oriented Programming Using C++ Unit 2
1/70
Govind Murari UpadhyayAssistant Professor
IITM, Janakpuri, Delhi
Object Oriented Programming Using
C++UNIT-2
1
7/29/2019 Objected Oriented Programming Using C++ Unit 2
2/70
Classes
A class is a way to bind the data and its associated functions
together.
It allows the data (and functions) to be hidden, if necessary
from external use.
When defining a class, we are creating a new abstract data
type that can be treated like any other built-in data type.
Generally, a class specification has two parts:
1. Class declaration
2 . Class function definitions
The class declaration describes the type and scope of its
members.
The class function definitions describe how the class functions
are implemented.
2
7/29/2019 Objected Oriented Programming Using C++ Unit 2
3/70
Classes
class identifier{access specifier: // Body of class having data members
statements; //and functions members enclosed by curlybraces {}.
}; //The class declaration ends with the semicolon. The class body comprises data members and function
members.
The data members comprise abstract data that applies toall the object of class and is relevant to the aim of the
program. The common characteristics of objects of class are
described by the function members of the class.
3
7/29/2019 Objected Oriented Programming Using C++ Unit 2
4/70
Definition of Member Functions in a Class Eg. Suppose it is required to assign the values of 10 and 13 to the X and Y
coordinates of a point and display the same.
Class point {
private:
int x;
int y;
public:
void getxy (int x_cord, int y_cord);
void showxy();
};
Here the member functions getxy() and shoxy() have been incorporated as
member functions of the class.
The member functions can be declared in two ways:
i) outside the class definition
ii) inside the class definition
Irrespective of the place of definition, the function should perform the same task.
Therefore, the code for the function body would be identical in both the cases.
4
7/29/2019 Objected Oriented Programming Using C++ Unit 2
5/70
DEFINING A MEMBER FUNCTION OUTSIDE THE CLASS
For defining a function outside the class body one has to use the scope
resolution operator (::).
An illustration is given below.
type class_name :: Function_name (type parameter1, - - -, - - -, type parameter
n)
{ statements ; } // function body
Here type refers to the type of the data returned by the function, it is followed
by name of the class, then the scope resolution operator followed by function
name and parameters in brackets.
5
7/29/2019 Objected Oriented Programming Using C++ Unit 2
6/70
Program
This is followed by body of function in braces{}.
#include class Market
{ // start of class declaration
public:
void Display(); // function prototype
}; // end of classvoid Market::Display () //function definition outside the class
{cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
7/70
Inside the Class Definition A method of defining a member function is to replace the function declaration by
the actual function definition inside the class.
Small functions may be defined inside the class definition. Note that as the member functions are defined inside the class definition, there
are no semicolons after the function definitions.
When a function is defined inside a class, it is treated as an inline function.
#include
class point{
private:
int x;
int y;
public:void getxy (int x_cord, int y_cord)
{
x = x_cord;
y = y_cord;
} 7
7/29/2019 Objected Oriented Programming Using C++ Unit 2
8/70
void showxy();
}; // end of class
void point :: showxy()
{
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
9/70
The Scope Resolution Operator
As you know, the :: operator links a class name with a member name in order
to tell the compiler what class the member belongs to.
However, the scope resolution operator has another related use: it can allow
access to a name in an enclosing scope that is "hidden" by a local declaration of
the same name.
For example, consider this fragment:
int i; // global i
void f() {
int i; // local i
i = 10; // uses local i
. . . }
As the comment suggests, the assignment i = 10 refers to the local i. But what if
function f() needs to access the global version ofi? It may do so by preceding the i
with the :: operator, as shown here.
9
7/29/2019 Objected Oriented Programming Using C++ Unit 2
10/70
int i; // global i
void f()
{
int i; // local i
::i = 10; // now refers to global i
. . . }
10
7/29/2019 Objected Oriented Programming Using C++ Unit 2
11/70
Information (Data) Hiding: Data is hidden inside the class, so that it cannot be accessed even by mistake by any function
outside the class.
C++ imposes a restriction to access both the data and functions of a class.
It is achieved by declaring the data part as private. All the data and functions defined in aclass are private by default.
#include
class part {
private:
int modelno, partno;
float cost;public:
void setpart(int mn, int pn, int c) {
Modelno=mn;
Partno=pn;
Cost=c; }
Void showpart() {
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
12/70
void main()
{
part p1, p2;
p1.setpart(1996, 23, 1250.50);
p2.setpart(2000, 243, 2350.50);
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
13/70
DECLARATION OF CLASS The form of code used for declaring a class is illustrated below.
class X // class is keyword, X is the name of class
{
private: //access label private
memberA; // memberA is a private member of class X.
protected: // access label protected
memberB; // MemberB is protected member...... // dotted line stands for other data or functions
public: //access label public
......
memberC; //memberC is a public member
private: //a access label may be repeated
memberD; // memberD is also a private member of class X
};
13
7/29/2019 Objected Oriented Programming Using C++ Unit 2
14/70
ACCESS SPECIFIERS private, protected and public
PRIVATE:
The class members written under the access label private are
accessible by class function members orfriend functions and thefunctions of friend classes.
The keywordfriend provides this specialprivilege to the functionor class declared asfriend in the class body.
The data or functions declared private cannot be accessedfrom
outside the class. The objects of the class can access the private members only
through the public function members of the class.
This property of class is also called information hiding.
However, with the help of pointers one can indirectly access
private data members provided the class contains at least onepublic data member. Generally data members are declared private.
The intention is to hide as much information about data andimplementation of class as possible.
This also helps against accidental change in object data members.
The functions members are in general declared public. 14
7/29/2019 Objected Oriented Programming Using C++ Unit 2
15/70
PROTECTED:
The class members declared protected are accessible by the
function members of same class andfriend functions andfriend classes as well as by functions of derived classes.
For all otheroperations protected members are similar toprivate members.
PUBLIC:
The class members declared public are accessible from insideor outside the class.
Some of the public functions of class provide interface foraccessing the private and protected members of the class.
For instance, initialization of a class object with private orprotected data is always carried through public functions.
Some public function also provide interface for other classes.
15
7/29/2019 Objected Oriented Programming Using C++ Unit 2
16/70
class with only one public function
#include
class Market // Market is name of class.{ //The marks beginning of class
declaration.
public: // Access label public
void Display() // Definition of a public function Display (){ cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
17/70
INITIALIZING PRIVATE DATA MEMBERS An object of a class is constructed when its data members are initialized.
If data is declared private, the initialization is carried by a public function
which may be a constructor function.
The data members x, y and z are declared private. For accessing the
private data members we need a public function.
For defining the same function outside the class body, first we have to
declare its prototype in the class as,void Setprice (int , int , int );
and put the definition outside the class as given below.
void Market ::Setprice (int a , int b , int c )
{x = a, y = b , z = c ;}
The general practice is to declare the function prototype inside the class
and to define the same outside the class.
The difference between the two is that functions defined inside the body
of class are taken as inline functions while the ones defined outside the
class body are called at the time of execution.17
7/29/2019 Objected Oriented Programming Using C++ Unit 2
18/70
Program
#include
class Market {
private :
int x,y,z;
public:
void Display1()
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
19/70
initializing public data members
#include
class Rect { // beginning of class
public:int x ,y; // data declared public
int Area( )
{return x*y; }
}; // End of class
int main(){
Rect R1; //R1 is an object of class Rect
R1.x = 8; // accessing data members directly
R1.y = 5;
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
20/70
CLASS WITH AN ARRAY AS DATA MEMBERThe class data or functions may have arrays. In the following program the
private data is an array.
#include class List {
private : //Access label private
int x[4]; // Array data
public:
void Display1() // Definition of function Display1()
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
21/70
void List ::Setprice (int a[4] ) // Definition of Setprice ()
{
for ( int j = 0; j< 4; j++)x[j] = a [j] ;
}
void main()
{
List L1; // L1 is an object of class List
int P[4] = {6,5,4,8} ;
L1.Setprice(P) ; // P is const pointer to the array
L1. Display1();
L1.Display2();
}
21
7/29/2019 Objected Oriented Programming Using C++ Unit 2
22/70
CLASS WITH AN ARRAY OF STRINGS AS DATA MEMBER
#include
#include
class List {
private :
int x[4]; // Array data
char Names[4][20] ; // two dimensional array
public:void Display1()
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
23/70
void List :: Setmarks (int a[4] ) //Definition of setmarks ()
{for ( int j = 0; j< 4; j++) // outside the class
x[j] = a [j] ;}
void List:: Setnames(char b[4][20] ) //Definition of Setnames
{for ( int m = 0 ; m
7/29/2019 Objected Oriented Programming Using C++ Unit 2
24/70
Nesting of Member Functions
A member function of a class can be called only by an objectof that class using a dot operator.
However, there is an exception to this.
A member function can be called by using its name insideanother member function of the same class.
#include
using namespace std;class set
{
int m, n;
public:void input(void);
void display(void);
int largest(void);
};24
7/29/2019 Objected Oriented Programming Using C++ Unit 2
25/70
int set :: largest(void)
{
if(m >= n)
return(m);
else
return(n);}
void set :: input(void)
{
coat "Input values of m and n" \n";
cin m n;
}
void set :: display(void){
cout Largest value largest() \n"; // calling member function
}
int main()
{
set A;
A.input();A.display();
return 0;
}
25
7/29/2019 Objected Oriented Programming Using C++ Unit 2
26/70
CLASS CONSTRUCTOR AND DESTRUCTOR FUNCTIONS
A constructor function is a public function and has same name as that of
the class.
It is used to initialize the object data variables or assign dynamic memory
in the process of creation of an object of the class so that the object
becomes operational.
Whenever a new instance or an object of the class is declared the
constructor is automatically invoked and allocates appropriate size ofmemory block for the object.
The constructor function simply initializes the object. It does not return
any value. It is not even void type.
So nothing is written for its type. The general characteristics of constructor
functions are given below.(i) Constructor function has same name as that of the class.
(ii) It is declared as a public function.
(iii) It may be defined inside the class or outside the class. If it is defined outside the class
its prototype must be declared in the class body.
(iv) It does not return any value, nor it is oftype void. So no type is written for it.
(v) The constructor is automatically called whenever an object is created. 26
7/29/2019 Objected Oriented Programming Using C++ Unit 2
27/70
destructor
The destructor function removes the object from the
computer memory after its relevance is over. For a local object the destructor is called at the end of the block
enclosed by the pair of braces { } wherein the object is created
and for a static object it is called at the end of main() function.
It releases the memory occupied by the object and returns it toheap. The destructor function also has same name as class but
it is preceded by the tilde symbol (~) and has no parameters.
It is a good programming practice to provide a destructor
explicitly. If it is not provided explicitly in the program it isprovided by the system.
27
Program
7/29/2019 Objected Oriented Programming Using C++ Unit 2
28/70
Program#include class Cubicle {
private:
int x, y, z;
public:
Cubicle ( int , int, int ); //constructor prototype
int volume() {return ( x*y*z);}
} ; // End of class
Cubicle::Cubicle(int a, int b, int c ) // Constructor
{x = a, y = b, z = c ; // defined outside class
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
29/70
TYPES OF CONSTRUCTORS
At least one parameter should be different or at least of different type. The
different types of constructors are listed below.
(i) Default Constructor
(ii) Parameterized Constructor
(iii) Copy constructor
Default constructorA constructor that accepts no parameters is called the default constructor. The
default constructor for class A is A::A(). If no such constructor is defined,
then the compiler supplies a default constructor.
29
7/29/2019 Objected Oriented Programming Using C++ Unit 2
30/70
Parameterized ConstructorsThe constructors that can take arguments are called parameterized
constructors.
#include
class integer{
int m, n;
public:
integer(int, int); // constructor declaredvoid display(void)
{
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
31/70
int main()
{
integer int1(0,100); // constructor called
Implicitly
integer int2 = integer(25, 75); //constructor called
explicitly
cout "\nOBJECT1 "\n;int1.display();
cout "\n08JECT2 \n; int2.display();return 0;
}
31
http://h/nOBJECrrhttp://h/n08JECI2'http://h/n08JECI2'http://h/n08JECI2'http://h/nOBJECrrhttp://h/nOBJECrr7/29/2019 Objected Oriented Programming Using C++ Unit 2
32/70
Copy constructor
A constructor can accept a reference to its own class as a parameter.
Program of all types of constructors
#include
class Cubicle {
private:
int x, y, z;
public:
Cubicle () { x = 3, y = 4, z = 2 ; // default constructor
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
33/70
Cubicle (int a, int b, int c ){x = a, y = b , z= c;
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
34/70
THE this POINTER The word this is a keyword of C++ and is the name of pointer
to an object of a class.
When an object is created, the compiler creates this pointerwhich keeps the address of the object.
Pointer this is not a part of object but object has access to itor we can say an object has access to its own address.
When the object calls a member function of the class, thispointer becomes implicitargument of the function and thefunction processes the data of the object.
#include
class Cuboid {
public:Cuboid(int L,int W,int H ){this ->x=L ,(*this).y=W ,this->z=H;}
// the above function is constructor
int surface_area( );
int volume( );
34
void Display1() // Displays private data of object.
7/29/2019 Objected Oriented Programming Using C++ Unit 2
35/70
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
36/70
FRIEND FUNCTION TO A CLASS
A friend function to a class has access to all the members of the class
whether these are private, protected or public .
This characteristic makes it useful in many applications, particularly, in
overloading of operators.
However, the free access to all the members of a class goes against its
frequent use, because, it dilutes the information hiding capability of the
class. Since friendship is granted by the class, therefore, the class declaration
should contain the declaration that the function is friend of the class.
A friend function is not a member function of the class in which it is
declared as friend, and hence a friend function is defined outside the
class body. It starts with keywordfriend followed by the type of function and identifier
(name) for the function which is followed by a list oftypes of parameters
of the function enclosed in parentheses (). Itends with a semicolon.
36
7/29/2019 Objected Oriented Programming Using C++ Unit 2
37/70
The following points should be noted about friend functions to classes.
1. If a function F is friend to class B, then F can access all the members of class B.
2. The friendship is granted by the class and not extracted by the function.
Therefore, the friend function has to be so declared in the body of the class as
illustrated above.
3. Function prototype of friend function preceded by keywordfriend is declared
inside the class body but the function is defined outside the class body.
4. Friend function is not a member function of the class to which it is friend.
Therefore, the scope resolution operator is not required while defining the
friend function outside the class body.
5. A class may have any number of friend functions. And a function may be friendto any number of classes.
6. A friend function may be declared any where in the class. The access specifiers,
i.e. public, protected or private do not affect a friend function.
37
Program
7/29/2019 Objected Oriented Programming Using C++ Unit 2
38/70
Program#include
class Rect {
friend int Area(const Rect &a); // friend function Area
int x,y; // private by default
public:
Rect (int L, int W){ x = L,y = W;} // constructor function
}; // end of class
int Area (const Rect &b) // definition of friend function
{return b.x*b.y;}; // scope resolution operator not needed
int main()
{
Rect R1(5,6), R2(3,4) ; //declaration of two objects R1 and R2cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
39/70
ONE FUNCTION FRIEND OF MANY CLASSES
A function may be friend to many classes. This is illustrated in the following
program in which a function Display() is declared friend to two classes, i.e.
class Sqr and class Rect.
#include
using namespace std;
class Sqr; //pre-declaration of class
class Rect { // class Rect
int x,y; // private by default
public:
Rect ( int A, int B) { x = A, y = B;}
int area ( )
{return x*y;}friend void Display ( Rect R, Sqr S ); // friend function to Rect
};
39
class Sqr { // class Sqr
7/29/2019 Objected Oriented Programming Using C++ Unit 2
40/70
q { q
int side; // private by default
public:
Sqr (int C){ side = C;}
int Area ( ){return side*side;}
friend void Display (Rect R , Sqr S ); // friend function to Sqr
}; //end of class
void Display ( Rect R, Sqr S) // Definition of friend function
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
41/70
FRIEND CLASSES
When all or most of the functions of a class need access to data members
and function members of another class, the whole class may be declared
friend to the class.
For instance, if the functions of a class say class A need to access the
public, private and protected members of another class say class B, the
class A may be
Class B
{friend class A; //declaration that class A is friend of B
Private:
statements
friend class C; //declaration that class C is friend of B
public:
Other_statements;
};
41
CHARACTERISTICS OF FRIEND CLASSES
7/29/2019 Objected Oriented Programming Using C++ Unit 2
42/70
CHARACTERISTICS OF FRIEND CLASSESThe following characteristics of friend classes should be noted.
1. If a class A is a friend of class B, then functions of A can access all the members of
B.
2. Ifclass A is a friend of class B, it does not mean that class B is also friend of class A.
The C++ friendship is not reciprocal.
3. Friendship is granted by the class whose members are to be accessed. If a class A
is friend ofclass B, it has to be so declared in the definition of class B.
4. Ifclass A is friend of class B and class B is friend of class C, it does not mean thatclass A is also friend ofclass C or class B is friend of class A or class C is friend of
class B or class A.
The C++ friendship is neither transmitted nor it is reciprocal.
5. A class may be friend to more than one class. And a class may have more than one
class as friends. There is no limit on the number of friends of a class.
42
Program
7/29/2019 Objected Oriented Programming Using C++ Unit 2
43/70
Program#include
class Cuboid {
friend class paint; // Declaration of friend class
public:
void sides(int , int, int);
int Area();
int volume();
int x , y, z;}; //end of class Cuboid
void Cuboid:: sides (int L, int W, int H )
{x = L, y = W,z = H; } // Setting the sides of Cuboid
int Cuboid::Area() //Definition of area
{return 2*(x*y +y*z +z*x);}
43
7/29/2019 Objected Oriented Programming Using C++ Unit 2
44/70
int Cuboid::volume() // definition of volume
{return x*y*z ;}
class paint{ //declaration of friend class paint
private:
int R;public:
paint () { R = 1;} // default constructor
paint ( int S) { R = S;} // parametric constructor
Cuboid C; // C is the object of class Cuboid
int area (){return C.Area ();}
int cost(int R , Cuboid C ) // R is the rate and C is object{return R* C.Area () ;} // of Cuboid. cost() is a function
};
int main()
{Cuboid C1 ; // C1 is object of class Cuboid
C1.sides (5,6,5 );
paint P1 ; // P1 is object of class paintint k = 4;
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
45/70
POINTER TO A CLASS
Pointer to a class may be declared in the same way as it is
done for integer or double numbers.
Let us have a class by name List and let L1 be an object of thisclass. Let ptr be the pointer to the class. For declaration of
pointer to List we may write the code as below.
List L1 ; // declaration that L1 is an object of class List
List *ptr; // declaration of pointer to Listptr = &(List) L1; // assignment of value to ptr
The last line may as well be written as ptr = &List (L1);
45
#include
class List {
7/29/2019 Objected Oriented Programming Using C++ Unit 2
46/70
class List {
private :
int x,y; //let x = the no of items, y = price of one item.
public:
void Setdata (int a, int b ) //A public function to access x,y.
{cout >a ;
cout b ;
x = a, y = b; }
void Display1 ( )
{cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
47/70
#include
class Rect {
int x ,y; // private by default
public:
void Setsides ( int L,int W ){ x = L ,y = W ;}
int Area( ) // Definition of function Area
{return x*y;} }; // end of class
int main() {
Rect R1,R2,R3;
void (Rect:: *ptrSet)(int,int) = & Rect :: Setsides;
(R1.*ptrSet) (20,15);
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
48/70
#include
class Rect {
friend int Area(Rect a); // friend function
int x, y; // data members private by default
public:friend double cost(Rect a, double); // another friend function
Rect (int L,int W){ x = L,y = W;} // constructor
}; // end of class
int Area (Rect b) // Definition of area using pointers
{ int Rect :: *ptrx = &Rect :: x; //ptrx is pointer for x
int Rect :: *ptry = &Rect :: y; // ptry is pointer for yRect *ptrb = &b; // ptrb is pointer to object b
return b.*ptrx * b.*ptry ;};
double cost(Rect b , double m)
{return b. x* b. y * m ;}
int main()
{ double n = 4.5;Rect R1(5,6), R2(3,4) ;
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
49/70
STATIC DATA MEMBERS OF A CLASS
Objects of a class keep their own copy of data members of class.
In certain situations a part of data may be same for all objects of a class.
In such cases instead of every object keeping an individual copy of this data, it
would be prudent if one copy of the data is shared by all the objects of class,
because, this would save memory space, particularly, when the common data is
large.
For such applications the common data may be declared static. The static data may
be declared under any one of the three access specifiers, i.e. public, protected orprivate.
A public static data member may be accessed directly through any object of the
class because it is same for all the objects.
The code comprises the object name followed by dot operator followed by name
of data member. Static data member declared private or protected may be accessed through the
corresponding public functions of the class.
49
#include
7/29/2019 Objected Oriented Programming Using C++ Unit 2
50/70
#include
class Cuboid {
public:
static int x; // x declared static
Cuboid( int W ): y(W) {} // constructor
static void Display ( ) // static function
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
51/70
int Cuboid::volume()
{return x*y*z ;}
int main()
{
Cuboid C1(6), C2(3) ;
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
52/70
STATIC FUNCTION MEMBER OF A CLASS A function member of a class may also be declared static provided its
arguments are also declared static or if it does not access any non-static
member of the class.
The pointer this associated with every object of class is applicable only tonon-static function members of the class.
The static function members of class do not have this pointer.
#include
class Cuboid {public:
Cuboid(int H):z(H) {} //constructor
static int Base_area (){ return x*y;} // static function
int surface_area( );
int volume( );
private:
static int x , y; // x and y declared static
int z ;
}; // end of class 52
7/29/2019 Objected Oriented Programming Using C++ Unit 2
53/70
int Cuboid :: x = 5; // static data member
int Cuboid :: y =8 ; // static data member
int Cuboid::surface_area() // definition of surface_area ()
{return 2*(x*y +y*z +z*x);}int Cuboid::volume() // definition of function volume()
{return x*y*z ;}
int main()
{
Cuboid C1(5), C2(8) ;
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
54/70
Local Classes Classes can be defined and used inside a function or a block. Such classes are
called local classes. Examples:void test(int a) // function
{
..................
class student // local class
{
...............
............... //Class definition
};
.............student s1 (a); // create student object
.............. // use student object
}
Local classes can use global variables (declared above the function) and staticvariables declared inside the function but cannot use automatic local variables.
The global variables should be used with the scope operator (::).
There are some restrictions in constructing local classes.
They cannot have static data members and member functions must be definedinside the local classes.
Enclosing function cannot access the private members of a local class.
However, we can achieve this by declaring the enclosing function as a friend.
54
DYNAMIC MEMORY MANAGEMENT FOR CLASS OBJECTS
7/29/2019 Objected Oriented Programming Using C++ Unit 2
55/70
OPERATORS NEW AND DELETE
The operator new allocates memory from the free store called heap while
the operator delete does just the opposite, it releases the memory by
deleting the object.
The released memory is added to heap for other uses. For allocation of
memory for an array we have the operator new[] and corresponding
operator delete[] for removing the array and releasing the memory.
For class objects new may be used for allocating memory for single objectwhile new[] may be used for creating an array of class objects.
Similarly single object is removed from memory by operator delete and
array of objects are removed by delete[] operator.
It must be noted that when new [] is used for allocation of memory, for
releasing the memory we must use delete [] and not simply delete. For example if you have created an array of objects by new[] and if you use
simply delete to remove the array, it will only delete the first object of the
array, the remaining objects would not get deleted.
So it will be only partial release of memory.
55
#include
l Li t {
7/29/2019 Objected Oriented Programming Using C++ Unit 2
56/70
class List {
private :
double x ; // x = weight in kg, y = price of one kg.
double y;
public:
void Setdata (double a, double b )
{x = a; y = b; }
void Display ( )
cout x;
couty;
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
57/70
class List {
private :
int x,y; // x = the no of items, y = price of one item.
public:
void Setdata (int a, int b ){x = a;
y = b; }
void Display ( ) {
cout x;
couty;
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
58/70
REFERENCES
Reference for a variable is also an alias or just another name
for the same variable.
The variable name and its reference-name both point to thesame block of memory where the value of variable is stored.
You must note that any change in the value of reference also
changes the value of variable.
For creating a reference first write the type of the variable forwhich the reference is being created then write reference
operator (&) followed by the name or identifier for the
reference.
Name of reference may be decided in the same way as it isdone for any variable.
58
#include
int main()
7/29/2019 Objected Oriented Programming Using C++ Unit 2
59/70
int main()
{int n = 100 ;
double Weight = 35.6;
char ch = S;
int& Count = n ; // Count is a reference to n.
double& W =Weight; // W is a reference to weight.
char& T = ch; // T is reference to ch.
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
60/70
NESTED CLASSES
A class may be declared inside another class.
The access specifiers work on nested class in the same way as
they act on other functions.
In the following illustrative program class Z is declared in class
Y in the public domain and class Y is in turn is declared in class
X in public domain.
All the three classes have private data for which appropriate
constructor functions are provided in each class.
The objects of each of these are declared in the main() and
values assigned to them.
60
#include
7/29/2019 Objected Oriented Programming Using C++ Unit 2
61/70
using namespace std;
class X
{private:
int x ;public:
X (int a ) {x = a;}
int getx () { return x ;}
class Y // nested class Y declared in class X
{private:
int y;
public :
Y( int b ) {y = b;}
int gety (){return y ;}
class Z // class Z declared in class y
{ private:
int z ;
public :
Z (int c ) { z = c;}61
int getz () { return z;}
7/29/2019 Objected Oriented Programming Using C++ Unit 2
62/70
int getz () { return z;}
}; // end of class Z
}; // end of class Y
}; // end of class Xint main()
{ X x_object (5);
X::Y y_object (10);
X::Y::Z z_object (20);
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
63/70
When a program consists of a large numbers of functions considerable
time of computer is wasted in the function call routine that it has to
follow.
When a function is called, the processor saves the present status of thecurrent program, evaluates the function and returns to resume the
ongoing program.
In case of frequently occurring small functions the overburden of function
call may be considerable and can make the program inefficient.
So the concept ofinline function is evolved. We define the function onlyonce in the program. It is preceded with key word inline as illustrated
below. The compiler substitutes the code of the function where ever it is
called in the program. An illustration of an inline function definition is
given below.
inline int Cube(x)
{return x*x*x ;}
63
The inlining does not work for the following situations :
7/29/2019 Objected Oriented Programming Using C++ Unit 2
64/70
The inlining does not work for the following situations :
1. For functions returning values and having a loop or a switch or a goto
statement.
2. For functions that do not return value and having a return statement.
3. For functions having static variable(s).
4. If the inline functions are recursive (i.e. a function defined in terms of
itself).
The benefits of inline functions are as follows:1. Better than a macro.
2. Function call overheads are eliminated.
3. Program becomes more readable.
4. Program executes more efficiently.
64
THE inline FUNCTIONS
7/29/2019 Objected Oriented Programming Using C++ Unit 2
65/70
THE inline FUNCTIONS#include
inline int Power(int x, int n) // inline function
{int P = 1; // definition
for (int i =0; i
7/29/2019 Objected Oriented Programming Using C++ Unit 2
66/70
Function Overloading
Function overloading is the process of using
the same name for two or more functions. The secret to overloading is that each
redefinition of the function must use either
different types of parameters or a differentnumber of parameters.
It is only through these differences that the
compiler knows which function to call in anygiven situation
66
#include
7/29/2019 Objected Oriented Programming Using C++ Unit 2
67/70
int myfunc(int i); // these differ in types of parameters
double myfunc(double i);
int main()
{
cout
7/29/2019 Objected Oriented Programming Using C++ Unit 2
68/70
Default Function Arguments
A function can be called without specifying all its arguments.
The function declaration must provide default values for thosearguments that are not specified.
A C++ function prototype can declare that one or more of the
functions parameters have default values.
When a call to the function omits the correspondingarguments, the compiler inserts the default values where it
expects to see the arguments.
68
Garbage collection
7/29/2019 Objected Oriented Programming Using C++ Unit 2
69/70
Garbage collection
Garbage collection is an automatic memory management
feature in many modern programming languages, such as Java
and languages in the .NET framework.
In older programming languages, such as C and C++, allocating
and freeing memory is done manually by the programmer.
Memory for any data that can't be stored within a primitive
data type, including objects, buffers and strings, is usuallyreserved on the heap.
When the program no longer needs the data, the programmer
frees that chunk of data with an API call.
Because this process is manually controlled, human error canintroduce bugs in the code.
Memory leaks occur when the programmer forgets to free up
memory after the program no longer needs it.
69
7/29/2019 Objected Oriented Programming Using C++ Unit 2
70/70