Class & Object

Download as pdf or txt
Download as pdf or txt
You are on page 1of 121

CLASS & OBJECT

 Class: A Class is a user defined data type to


implement an abstract object. Abstract means
to hide the details. A Class is a combination of
data and functions.

 Data is called as data members and functions


are called as member functions.
 Abstract data type:-
 A data type that separates the logical properties
from the implementation details called Abstract
Data Type(ADT).

 An abstract data type is a set of object and an


associated set of operations on those objects.

 ADT supports data abstraction, encapsulation and


data hiding.
 Examples of ADT are:-
 Boolean
 Integer built in ADT
 Array
 Stack
 Queue
 Tree search structure User defined
ADT
 Boolean {operations are AND,OR,NOT and
values are true and false}
 Queues{operations are create , dequeue,inqueue and
values are queue elements}
Class definition
 A class definition begins with the keyword
class.
 The body of the class is contained within a set
of braces, { } ; (notice the semi-colon).

class class_name Any valid


{ identifier
….
….
Class body (data member +
….
methods)
methods
};
 Within the body, the keywords private: and
public: specify the access level of the
members of the class.
 the default is private.

 Usually, the data members of a class are


declared in the private: section of the class and
the member functions are in public: section.
 Data member or member functions may be public,
private or protected.

 Public means data members or member functions


defining inside the class can be used at outside the
class.( in different class and in main function)

 Member access specifiers


 public:
 can be accessed outside the class directly.
 The public stuff is the interface.
 private:
 Accessible only to member functions of class
 Private members and methods are for internal use only.

 Private means data members and member functions


can’t be used outside the class.

 Protected means data member and member


functions can be used in the same class and its
derived class (at one level) (not inmain function).
PRIVATE

PUBLIC
class class_name
{
private: private members or methods



public:
… Public members or methods


};
 This class example shows how we can
encapsulate (gather) a circle information into
one package (unit or class)
No need for others classes to access
class Circle and retrieve its value directly. The
{ class methods are responsible for
that only.
private:
double radius;
public:
void setRadius(double r); They are accessible from outside
double getDiameter(); the class, and they can access the
double getArea(); member (radius)
double getCircumference();
};
Class Example (Problem)
#include<iostream.h> void main()
#include<stdio.h> {
class student student s;
{ cout<<“enter the rollno.:”;
int rollno; cin>>s.rollno;
char name[20]; cout<<“enter the name:”;
}; gets(s.name);
cout<<“rollno:”<<s.rollno;
cout<<“\nname:”;
puts(s.name);
}
Class Example (Solution)
#include<iostream.h> void main()
#include<stdio.h> {
class student student s;
{ cout<<“enter the rollno.:”;
public: cin>>s.rollno;
int rollno; cout<<“enter the name:”;
char name[20]; gets(s.name);
}; cout<<“rollno:”<<s.rollno;
cout<<“\nname:”;
puts(s.name);
}
Implementing class methods
 There are two ways:
1. Member functions defined outside class
 Using Binary scope resolution operator (::)
 “Ties” member name to class name
 Uniquely identify functions of particular class
 Different classes can have member functions with same name
 Format for defining member functions
ReturnType ClassName::MemberFunctionName( ){

}
Member Function
Defining Inside the Class
#include<iostream.h>
#include<stdio.h>
class student
{ Data Members (Private : in this example)
int rollno;
char name[20];
public:
void getdata()
{
cout<<“enter the rollno.:”; Member Functions (Public: in this example)
cin>>rollno;
cout<<“enter the name:”;
gets(name);
}
void putdata()
{
cout<<“rollno:”<<rollno;
cout<<“\nname:”;
puts(name);
}
};
Calling member function
void main()
{
student s;
s.getdata();
s.putdata();
}
Member Function
Defining Outside the Class
#include<iostream.h> void student: :: putdata()
#include<stdio.h> {
class student cout<<“rollno:”<<rollno;
{ cout<<“\nname:”;
int rollno; puts(name);
char name[20]; }
public: void main()
void getdata(); {
void putdata(); student s;
}; s.getdata();
void student :: getdata() s.putdata();
{ }
cout<<“enter the rollno.:”;
cin>>rollno;
cout<<“enter the name:”;
gets(name);
}
Characteristics of member
function
 Different classes have same function name. the
“membership label” will resolve their scope.
 Member functions can access the private data of the
class .a non member function cannot do this.(friend
function can do this.)
 A member function can call another member function
directly, without using the dot operator.
Accessing Class Members
 Operators to access class members
 Identical to those for structs
 Dot member selection operator (.)
 Object
 Reference to object
 Arrow member selection operator (->)
 Pointers
Static members
 The data and functions of the class may be declared static in
the class declaration.

 The static data members have similar properties to the C static


variable.

 The static data members is initialized with zero when the first
object of its class is created. No other initialization is
permitted.

 Only one copy of that member is created for the entire class
and is shared by all the objects of that class, no matter how
many objects are created.

 It is visible only within the class, but its lifetime is the entire
program.
Static member function
 Like static data members we can also declare static
member functions.
 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 (instead of its objects) as folows
 Class name:: function name.
Example of static members Int test::count;
#inlcude<iostream.h> Int main()
Class test {
{
Int code;
test t1,t2;
Static int count; t1.setcode();
Public: t2.setcode();
Void setcode()
{ test::showcount();
Code=++count; test t3;
}
Void showcode() t3.setcode();
{ test::showcount();
Cout<<“object number “<<code<<endl; t1.showcode();
}
Static void showcount() t2.showcode();
{ t3.showcode();
Cout<<“count :”<<count;
} Return 0;
};
}
Class inside a function
 When a class declared within a function, it is known as
local class.
 A local class is known only to that function and
unknown outside it.
 All member functions must be defined within the class
declaration.
 The local class may not use local variables of the
function in which it is declared except static and extern
local variables declared within the function.
 No static variables may be declared inside a local class.
 Due to these restrictions local class is not popular in C++
programming.
Objects
 An object is an instance of a class.

 An object is a class variable.

 Is can be uniquely identified by its name.

 Every object have a state which is represented by the


values of its attributes. These state are changed by
function which applied on the object.
State identity and behavior of
objects
 Every object have identity , behaviour and state.

 The identity of object is defined by its name, every


object is unique and can be differentiated from other
objects.

 The behavior of an object is represented by the


functions which are defined in the object’s class. These
function show the set of action for every objects.

 The state of objects are referred by the data stored


within the object at any time moment.
Creating an object of a Class
 Declaring a variable of a class type creates an object. You
can have many variables of the same type (class).
 Also known as Instantiation
 Once an object of a certain class is instantiated, a new
memory location is created for it to store its data members
and code
 You can instantiate many objects from a class type.
 Ex) Circle c; Circle *c;
Class item
{
……….
,,,,,,,,,,,,,
}x,y,z;

We have to declared objects close to the place where they are needed
because it makes easier to identify the objects.
Object types
 There are four types of objects
1. External (global )objects
1. This object have the existence throughout the lifetime of the program and
having file –scope.

2. Automatic(local)objects
1. Persistent and visible only throughout the local scope in which they are
created.

3. Static objects
1. Persistent throughout a program but only visible within their local scope.

4. Dynamic objects
1. Lifetime may be controlled within a particular scope.
Memory Allocation of Object
class student
{ rollno – 2 bytes

int rollno;
char name[20]; name- 20 bytes
int marks;
};
student s; marks- 2 bytes

24 bytes s
Array of objects

 The array of class type variable is known as array of


object.
 We can declare array of object as following way:-
Class _name object [length];
Employee manager[3];
1. We can use this array when calling a member function

2. Manager[i].put data();

3. The array of object is stored in memory as a multi-

dimensional array.
Object as function arguments
 This can be done in two ways:-

 A copy of entire object is passed to the function.


 ( pass by value)

 Only the address of the object is transferred to the


function. (pass by reference)
( pass by value)
 A copy of the object is passed to the function, any
changes made to the object inside the function do not
affect the object used to call function.

(pass by reference)
 When an address of object is passed, the called
function works directly on the actual object used in
the call. Means that any change made in side the
function will reflect in the actual object.
Passing Object
#include<iostream.h>
class Complex void Complex : : sum ( complex A, complex B)
{ {
float real, imag; real = A.real + B.real;
public:
void getdata( ); imag= A.imag + B.imag;
void putdata( ); }
void sum (Complex A, Complex B);
};
void Complex : : getdata( ) void main( )
{ {
cout<<“enter real part:”;
cin>>real; Complex X,Y,Z;
cout<<“enter imaginary part:”; X.getdata( );
cin>>imag; Y.getdata( );
}
void Complex : : putdata( ) Z.sum(X,Y);
{ Z.putdata( );
if (imag>=0)
}
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
}
Passing Object
#include<iostream.h>
class Complex void Complex : : sum ( Complex A, Complex B)
{ {
float real, imag; real = A.real + B.real;
public:
void getdata( ); imag= A.imag + B.imag;
void putdata( ); }
void sum (Complex A, Complex B);
};
void Complex : : getdata( ) void main( )
{ {
cout<<“enter real part:”;
cin>>real; Complex X,Y,Z;
cout<<“enter imaginary part:”; X.getdata( );
cin>>imag; Y.getdata( );
} X Y Z
void Complex : : putdata( ) Z.sum(X,Y);
{ Z.putdata( );
if (imag>=0)
}
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
}
Passing Object
#include<iostream.h>
class Complex void Complex : : sum ( Complex A, Complex B)
{ {
float real, imag; real = A.real + B.real;
public:
void getdata( ); imag= A.imag + B.imag;
void putdata( ); }
void sum (Complex A, Complex B);
};
void Complex : : getdata( ) void main( )
{ {
cout<<“enter real part:”;
Complex X,Y,Z; 5 7
cin>>real;
6 8
cout<<“enter imaginary part:”; X.getdata( );
cin>>imag; Y.getdata( );
} X Y Z
void Complex : : putdata( ) Z.sum(X,Y);
{ Z.putdata( );
if (imag>=0)
}
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
}
Passing Object
#include<iostream.h>
class Complex void Complex : : sum ( Complex A, Complex B)
{ {
float real, imag; real = A.real + B.real;
public:
void getdata( ); imag= A.imag + B.imag;
void putdata( ); }
void sum (Complex A, Complex B);
};
void Complex : : getdata( ) void main( )
{ {
cout<<“enter real part:”;
Complex X,Y,Z; 5 7
cin>>real;
6 8
cout<<“enter imaginary part:”; X.getdata( );
cin>>imag; Y.getdata( );
} X Y Z
void Complex : : putdata( ) Z.sum(X,Y);
{ Z.putdata( );
if (imag>=0) 5 7
} 6 8
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”; A B
}
Passing Object
#include<iostream.h>
class Complex void Complex : : sum ( Complex A, Complex B)
{ {
float real, imag; real = A.real + B.real;
public:
void getdata( ); imag= A.imag + B.imag;
void putdata( ); }
void sum(Complex A, Complex B);
};
void Complex : : getdata( ) void main( )
{ {
cout<<“enter real part:”;
Complex X,Y,Z; 5 7 12
cin>>real;
6 8 14
cout<<“enter imaginary part:”; X.getdata( );
cin>>imag; Y.getdata( );
} X Y Z
void Complex : : putdata( ) Z.sum(X,Y);
{ Z.putdata( ); + =
if (imag>=0) 5 7
} 6 8
cout<<real<<“+”<<imag<<“i”; + =
else
cout<<real<<imag<<“i”; A B
}
Passing Object
#include<iostream.h> void complex : : sum ( Complex A, Complex B)
class Complex {
{ real = A.real + B.real;
float real, imag; imag= A.imag + B.imag;
public: }
void getdata( );
void putdata( ); void main( )
void sum (Complex A, Complex B); {
}; Complex X,Y,Z;
void Complex : : getdata( ) X.getdata( );
{ Y.getdata( );
cout<<“enter real part:”; Z.sum(X,Y); 5 7 12
cin>>real;
cout<<“enter imaginary part:”;
Z.putdata( ); 6 8 14
}
cin>>imag;
} X Y Z
void Complex : : putdata( )
{ + =
if (imag>=0) 12 + 14 i 5 7
cout<<real<<“+”<<imag<<“i”; 6 + 8 =
else
cout<<real<<imag<<“i”; A B
}
Returning Object
#include<iostream.h> Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( )
{
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
}
Returning Object
#include<iostream.h> Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( )
{
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else X Y Z
cout<<real<<imag<<“i”;
}
Returning Object
#include<iostream.h> Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{ 6 8
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else X Y Z
cout<<real<<imag<<“i”;
}
Returning Object
#include<iostream.h> Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{ 6 8
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else X Y Z
cout<<real<<imag<<“i”;
} 7
8

B
Returning Object
#include<iostream.h> Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{ 6 8
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else X Y Z
cout<<real<<imag<<“i”;
} 7
8

B
Returning Object
#include<iostream.h> Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{ 6 8
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else X Y Z
cout<<real<<imag<<“i”;
} 7 12
8 14

B temp
Returning Object
#include<iostream.h> Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{ 6 8
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else X Y Z
cout<<real<<imag<<“i”;
} 7 12
8 14

B temp
Returning Object
#include<iostream.h> Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7 12
{ 6 8 14
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else X Y Z
cout<<real<<imag<<“i”;
} 7 12
8 14

B temp
Returning Object
#include<iostream.h> Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7 12
{ 6 8 14
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else X Y Z
cout<<real<<imag<<“i”;
} 7 12
12 + 14 i 8 14

B temp
C++ garbage collection
 In c++ the garbage collection task is accomplised by
mark and sweep algorithm.

 In this approach the garbage collector periodically


examines every single pointer in our program and
find that the memory is still in use. At the end of the
cycle, any memory that has not been marked is
deemed to be not in use and is freed.
Steps to implement the garbage
collection
 Mark and sweep algorithm could be implemented in c++
if we arere willing to do the following:

1. Register all pointers with the garbage collector so that it


can easily walk through the list of all pointers.

2. Sub-class all objects from a mix-in class, that allows the


garbage collectors to mark an object as in-use.

3. Protect concurrent access to objects by making sure that


no changes to pointers can occur while the garbage
collector is running.
Memory management in c++
 Ways of memory allocation in c++
 Static memory allocation

 The memory allocation for variables ,during compilation time


itself is known as static memory allocation.

 Once the memory allocated at the compile time then it can not
be expanded nor be compressed to accommodate more or less
data during program execution.

 The size of memory to be allocated is known before compile


time and is fixed it can not be altered during execution.
 Int a[10];
Dynamic memory allocation

 The dynamic memory allocation is carried-out in


c++ using two operators “new” and “delete”.these
operators are use to allocate and free memory at
run time.
 Dynamic memory allocation helps in memory
saving and easy to change memory allocation.
 In c++ dynamic memory allocation is control by
NEW and DELETE operator.
 The new operator return the memory pointer to the
pointer variable.
 Syntax:
Ptr= new data type;
Delete Ptr;
Ptr is pointer and data type is valid data type
 The difference between NEW and malloc function is that
NEW automatically calculates the size of operand , dos not
use size of operator and NEW does not require an explicit
type cast.
 Versions of NEW and DELETE
 in c++ NEW and DELTE should be used like malloc and free to
ensure the proper calling of constuctor and destructor for the
classes.
 Both have two versions
1. NEW and Delete
2. NEW[] and DELETE []
 First two are for pointers to single objects, and last two for
arrays of objects.
Difference between static and
dynamic memory allocation
Static memory allocation Dynamic memory allocation
Static memory is allocated automatically Dynamic memory is allocated only when
by compiler when definition statements there is explicit call to malloc, calloc or
are encountered. realloc function.
To make static memory allocation , the Amount of memory to be reserved can be
amount of the memory space to be given at the run time.
reserved should be known at the run time.
In static memory allocation sometimes Memory wastage is avoided due to
memory wastage occurs because memory memory allocation occur at run time.
is already known and it can not change.
Memory allocated at the compile time has Memory allocated at run time has
static lifetime. dynamic lifetime.
Its is faster it is slower
Meta class

 a meta class is a class whose instances are classes.


Just as an ordinary class defines the behavior of
certain objects, a meta class defines the behavior of
certain classes and their instances.

 a meta class is defines as class of the class.

 A meta class hold the attributes and function which


will appli to the class itself therefore it is class of
class.
Friend function
 C++ allows a way through which a function can
access the private data of a class.

 Such a function need not be a class member, it may


be member function of another class or may be non
member function.

 This function is called FRIEND FUNCTION. The


declaration should be preceded by keyword
FRIEND.
Class PQr  The function is defined
{ elsewhere in the program like
Private: normal function.
………
Public:  Function definition does not use
…… either keyword FRIEND or
…… scope operator.
Friend void abc();
};  Functions that are declared with
FRIEND keyword are known as
friend functions.
 A function can declared as friend in number of class.

 A friend function has full access right to access the


private members of class.

 Member function of one class can be friend of


another class.
Characteristics
 It is not in the scope of the class in which it has been
declared as friend.
 it is not in the scope of class so it cannot be called
using object of that class.
 It can be invoked like normal function ,without
object.
 It can be declared either in public or private part with
out affecting its meaning.

 Usually, it has the objects as arguments.

 Unlike member function, it cannot access the member


names directly and has to use an object name and dot
membership operator with each name. like
 A.h
Friend Function
#include<iostream.h> Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( )
{
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
}
Friend Function
#include<iostream.h> Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( )
{
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else X Y Z
cout<<real<<imag<<“i”;
}
Friend Function
#include<iostream.h> Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{ 6 8
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else X Y Z
cout<<real<<imag<<“i”;
}
Friend Function
#include<iostream.h> Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{ 6 8
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else X Y Z
cout<<real<<imag<<“i”;
} 5 7
6 8

A B
Friend Function
#include<iostream.h> Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{ 6 8
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else X Y Z
cout<<real<<imag<<“i”;
} 5 + 7 =
6 + 8 =
A B temp
Friend Function
#include<iostream.h> Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{ 6 8
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else X Y Z
cout<<real<<imag<<“i”;
} 5 + 7 = 12
6 + 8 = 14

A B temp
Friend Function
#include<iostream.h> Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7 12
{ 6 8 14
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else X Y Z
cout<<real<<imag<<“i”;
} 5 + 7 = 12
6 + 8 = 14

A B temp
Friend Function
#include<iostream.h> Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7 12
{ 6 8 14
if (imag>=0)
cout<<real<<“+”<<imag<<“i”; 12 + 14 i
else X Y Z
cout<<real<<imag<<“i”;
} 5 + 7 = 12
6 + 8 = 14

A B temp
 We can also declare all the member functions of one
class as the friend functions of another class. In this
case the first class is known as FRIEND class.

 This can be specified as follows :-


Class z
{
…………..
……
Friend class x;
};
A function friend in two classes
#include<iostream.h> Void max(XYZ m,ABC n)
Class ABC; {
Class XYZ If(m.x>=n.a)
Cout<<m.x;
{ int x;
Else
Public:
Cout<<n.a;
Void setvalue(int i)
}
{ x=i ; }
Int main ()
Friend void max(XYZ,ABC);
{
};
ABC abc;
Class ABC
abc..setvalue(10);
{ int a;
XYZ xyz;
Public:
Xyz.setvalue(20);
void setvalue(int i)
max(xyz,abc);
{ a=i ;}
Return 0;
Friend void max(XYZ,ABC);
}
};
Pass by reference
#include<iostream.h> Class class_2
Class class_2; { int value2;
Class class_1 public:
{ int value1; void indata( int a)
Public: { value2=a; }
void indata(int a) Void display()
{ value1=a; } { cout<<value2<<“\n”; }
Void display() Friend void exchange(class_1
{ cout<<value1<<“\n”; } &,class_2 &);
Friend void exchange(class_1 &, };
class_2 &);
};
Contd…
Void exchange(class_1 & x,class_2 C1.indata(100);
& y) C2.indata(200);
{ int temp=x.value1; Cout<<“values before
x.value1=y.value2; exchange”<<“\n”;
y.value2=temp; C1.dispaly();
} C2.display();
Int main() Exchange(c1,c2);
{ Cout<<“values after
class_1 c1; exchange”<<“\n”;
Class_2 c2; C1.display();
C2.display();
Return 0;
}
Define a class tour in C++ with the
description given below:
Private members:
tcode of type string
Noofadults of type integer
Noofkids of type integer
Kilometers of type integer
Totalfare of type float
Public members:
 A constructor to assign initial values as follows:
Tcode with the word “NULL”
Noofadults as 0
Noofkids as 0
Kilometers as 0
Totalfare as 0
 A function assignfare( ) which calculates and assigns the value of data member totalfare as follows:
for each adult
Fare (Rs.) For Kilometers
500 >=1000
300 < 1000 & >= 500
200 < 500
for each kid the above fare will be 50% of the fare mentioned in the above table for example:
if kilometers is 850, noofadults =2 and noofkids = 3
then totalfare should be calculated as
noofadults * 300 + noofkids * 150
I.e. 2 * 300 + 3 * 150 = 1050
 A function entertour( ) to imput the values of the data members tcode, noofadults, noofkids and
kilometers and invoke assignfare( ) function.
 A function showtour ( ) which displays the contents of all the data members for a tour.`````
class tour void entertour( )
{ {
char tcode[15]; cout<<“enter tcode:”;
int noofadults; gets(tcode);
int noofkids;
int kilometers;
cout<<“enter noofadults:”;
float totalfare; cin>>noofadults;
public: cout<<“enter noofkids:”;
tour( ) cin>>noofkids;
{ cout<<“enter kilometers=“;
strcpy(tcode,”null”); cin>>kilometers;
noofadults=0;
noofkids=0; }
kilometers=0; void showtour ( )
totalfare=0; {
} cout<<“tcode=“<<tcode;
void assignfare( ) cout<<“\nnumber of
{ adults=“<<noofadults;
if (kilometers>=1000) cout<<“\nnumber of kids=“<<noofkids;
totalfare= 500 * noofadults + 250 *
noofkids; cout<<“\nkilometers=“<<kilometers;
else if (kilometers>=500) cout<<“\ntotalfare=“<<totalfare;
totalfare= 300 * noofadults + 150 * }
noofkids;
else
};
totalfare= 200 * noofadults + 100 *
noofkids;
}
Define a class HOUSING in C++
with the following descriptions:
(4)
 private members:
 REG_NO integer (ranges 10-1000)
 NAME array of characters (string)
 TYPE character
 COST float
 Public members:
 function read_data( ) to read an object of HOUSING type.
 Function display ( ) to display the details of an object.
 Function draw_nos( ) to choose and display the details of 2
houses selected randomly from an array of 10 objects of type
HOUSING. Use random function to generate the registration
nos. to match with REG_NO from the array.
void display ( )
class HOUSING {
{ cout<<“Registration No.”<<REG_NO;
int REG_NO; cout<<“\nName=“;
char NAME[20], TYPE; puts(NAME);
float COST; cout<<“\nType=“<<TYPE;
public: cout<<“\nCost=“<<COST;
void read_data( ) }
{ void draw_nos( )
cout<<“Enter Registration Number=“; {
cin>>REG_NO; int no1, no2;
cout<<“Enter Name=“; randomize( );
gets(NAME); no1=random(1991)+10;
cout<<“Enter Type=“; no2=random(1991)+10;
cin>> TYPE; for (int i=0; i<10; i++)
cout<<“Enter Cost=“; if (arr[i].REG_NO==no1|| arr[i].REG_NO==no2)
cin>>COST; display();
} }
};
HOUSING arr[10];
function
function

 Void show(); function declaration


 Main()
 {
 Show(); function call
}
Void show() function definition
{
…………
……… function body
}
Function prototype
 Introduce first in c++.

 Prototype describe the function interface ti the compiler


by giving details (number and type of arguments and
return type)..

 Type function name (arguments list). ;


 Ex:-
 float add(int k,int g);
 float add(int k,g); illegal
 float add (int ,int){name of the arguments
are optional}
 In function definition arguments names are required
because the arguments must be refereced inside the
function ex:-

 Float volume(int a,float b,float c);


 {
 Float v=a * b * c;
 }

 The function calling should not include type names in the


argument list.
Call by reference
 When we pass arguments by reference then the argument
in the called function become alias to the actual arguments
in the calling function .

 When function is working its own arguments, its works


on the original arguments.

 In c++ this task is perform by making reference variable


to the actual arguments.
Call by value.

 When a function call passes arguments by value, the


called function creates a new set of variable and copies
the values of arguments into them, this process is known
as call by value.

 Function does not have access to the actual variables in


the calling program and can work on the copies of values.
Inline function

 Inline is a function that expanded in a line when it is invoked.


 The compiler replaces the function call by its corresponding
code.
 Syntax:
 Inline return type function name
 {
 Function body
 }
 Improve the execution speed.

 Reduces the memory requirement of function execution.

 All inline function must be defined before they called.

 The speed benefits of inline function diminish as the


function grows in size.

 A function definition in a class definition is an inline


function definition, even without the use of the inline
specifier.
 Where inline may not work
 For functions returning values , if a loop, switch, goto
statements.

 Functions not returning values, if return exists.

 If function contain static variables.

 If inline functions are recursive

 When function call becomes small compare to function


execution.
 #include<iostream.h>
 Inline float add(float x , float y)
 {
 Return (x+y);
 }
 Inline float sub(float p , float q )
 {
Return(p-q);
}
Int main()
{
Float a=12.34;
Float b=3.6
Cout<<add(a,b)<<endl;
cout<<sub(a,b)<<endl;
Return 0;
}
Default arguments

 A default argument is a value given in the function


declaration that the compiler automatically inserts if the
caller does not provide a value for that argument in the
function call.
 Syntax:

return_type f(…, type x = default_value,…);


Default arguments

 Default values are specified when the function is declared.

 We must add default values from right to left ,we can not
provide a default value to a particular arguments in the
middle of argument list.

 Default arguments are useful in situations where some


arguments always have the same value.
Default Arguments
(Examples)

 double pow(double x, int n=2)


 // computes and returns x n

The default value of the 2nd argument is 2.


This means that if the programmer calls pow(x), the
compiler will replace that call with pow(x,2), returning
x2
Default Arguments
(Rules)
 Once an argument has a default value, all the arguments
after it must have default values.
 Once an argument is defaulted in a function call, all the
remaining arguments must be defaulted.

int f(int x, int y=0, int n)


int f(int x, int y=0, int n=1)
// illegal
// legal
Examples:-

 Int mul(int I,int j=6,int l=9); legal


 Int mul(int I,int j=6,int l); illegal
 Int mul(int I=0,int j,int l=9); illegal
 Int mul(int I=0,int j=6,int l=9); legal

 Advantages:-
 We can default arguments to add new parameters to the
existing functions.
 Default arguments can be used to combine similar
functions into one.
Function overloading

 When using more than one functions with same name and
with different arguments in a program is known as
function overloading or function polymorphism.

 Function overloading is part of polymorphism.


Function overloading

 Function would perform different operations depending


on the argument list in function call.

 Correct function to be invoked is determined by checking


the number and type of arguments but not on return type
of function.

 Examples;-
 Int area(int,int);
 Int area(int ,float);
Function overloading
 Examples :-
Function prototype 1
 Int add(int a, int b);
 Int add(int a, int b, int c); Function prototype 2

 Double add(double x, double y); Function prototype 3


 Double add(int p ,double q); Function prototype4
 Double add(double p, int q);
Function prototype 5

 Function calls
 Add(5,19);
 Add(16,7.9); Add(12.4,3.5);
 Add (4,12,23); Add(3.4,7)
Function overloading
 A function call first match the prototype having the same
number and type of actual arguments and then calls the
appropriate function for execution…
Function overloading
 A function match includes following steps:-

1. Compiler first try to find exact match in which the types


of actual arguments are the same.

2. If exact match not found, compiler uses the integral


promotions to the actual arguments like char to int, float
to double.
Function overloading

3. When either of them fail then compiler uses built in


conversion to the actual arguments and then uses the
function whose match is unique.

4. If all of the steps fail then the compiler will try user
defined conversions in combination with integral
promotions and built in conversions to find a unique
match.
Constructors

and

Destructors
Constructor
 It is a member function which initializes the
objects of its class.

 A constructor has:
(i) the same name as the class itself
(ii) no return type ,not even void.

 It constructs the values of data member so


that it is called constructor.
 A constructor is called automatically
whenever a new object of a class is
created.

 You must supply the arguments to the


constructor when a new object is created.

 If you do not specify a constructor, the


compiler generates a default constructor
for you (expects no parameters and has
an empty body).
void main()
{
rectangle rc(3.0, 2.0);

rc.posn(100, 100);
rc.draw();
rc.move(50, 50);
rc.draw();
}

 Warning: attempting to initialize a data


member of a class explicitly in the class
definition is a syntax error.
Declaration and defination
Class complex
{
Int m,n;
Public:
complex();
};
complex :: complex ()
{
m=0;n=0;
}
 A constructor that accepts no parameters is
called default constructor.
characteristics
1. They should be declared in public section.
2. Invoked automatically when class objects are
created.
3. They do not have return types, not even void
and they can't return any value.
4. They cannot be inherited,though a derived
class can call the base class constructors.
5. They also default arguments like other
functions.
6. They implicitly call the NEW and DELETE
operators when memory allocation is required.
7. Constructors can not be virtual.
Parameterized constructors
 The constructors that can take arguments are
called parameterized constructors.

 It is used when we assign different value to


the data member for different object.

 We must pass the initial values as arguments


to the constructors when an object is
declared.
 This can be done in two ways:-
 By calling the constructors implicitly
 Class_name object(arguments);
 Ex:- simple s(3,67);

 This method also known as shorthand.

 By calling the constructors explicitly


 Class_name object =constructor(arguments);
 Ex:- simple s=simple(2,67);

 This statement create object s and passes the values 2

and 67 to it.
Example:-
#include<iostream.h> Int main()
Class integer {
{ int m,n; Integer i1(10,100);
public: Integer i2=integer(33,55);
integer(int,int); Cout<<“object 1”;
void display() i1.display();
{ cout<<“m”<<m; Cout<<“object 2”;
cout<<“n”<<n; } i2.display();
}; Return 0;
Integer::integer(int x,int y) }
{
m=x;
n=y;
}
Notes:-

 A constructor function can  Parameters of a


also be defined as INLINE constructor can be of any
function. type except that of the
class to which it belongs.
Class integer Class A
{ int m,n; {
public: ……….
integer (int x,int y)
…….
{ m=x;
n=y; Public:
}}; A(A);
}; is illegal
 A class can accept a  In this case the
reference of its own class constructor is called as
as parameter.
copy constructor.
Class A
{
………
……………
Public:
A(A&);
};
is valid
Copy constructor
 When a class reference is passed as parameters
in constructor then that constructor is called
copy constructor.
 A copy constructor is used to declare and
initialize an object from another object.
 Synatx:-
 Constructor _name (class_name & object);
 Integer (integer &i);
 Integer i2(i1);/integer i2=i1;
 Define object i2 and initialize it with i1.
 The process of initialization object through copy
constructor is known as copy initialization.

 A copy constructor takes a reference to an object


of the same class as itself as argument.
 #include<iostream.h> int main()
Class person {
{ public: Person timmy(10);
int age; Person sally(15);
Person(int a) Person timmy_clone = timmy;
{ age = a; } cout << timmy.age << " " <<
Person(person & x) sally.age << " " <<
timmy_clone.age << endl;
{ age=x.age;
timmy.age = 23;
}
cout << timmy.age << " " <<
}; sally.age << " " <<
timmy_clone.age << endl;
}
Dynamic constructors
 Constructors can also be used to allocate
memory while creating objects.
 This will allocate the right amount for each
object when the objects are not of the same
size.
 Allocation of memory to objects at the time of
their construction is known as dynamic
construction is known as “dynamic
construction of objects”.
 The memory is allocated by NEW operator.
void join (string &a,string & b);
#include<iostream.h> };
#include<string.h> void string:: join(striing&a,string &b)
Class string { length =a.length+b.length;
{ delete name;
char *name; name =new char [length+1];
int length; strcpy(name,a.name);
Public: strcpy(name,b.name);
string() }
{ Int main()
length =0; { char *first =“jon”;
name = newchar[length+1]; string name1(first),name2(tom),name3(jery),s1,s2;
} s1.join(name1.name2);
string(char *s) s2.join(s1,name3);
{ name1.display();
length=strlen(s); name2.display();
name=new char [length+1]; name3.display();
strcpy(name,s ); s1.display();
} s2.display();
Void display() return 0;
{ cout<<name<<“\n”;} }
Constructor overloading
{multiple constructor in a class}
 When more than one function is defined in a class ,
is known as constructor overloading.
 Example:-
Class integer
{ int m,n;
public:
integer()
{ m=0; n=0; }
Integer (int a,int b)
{ m=a;n=b }
Integer(integer&i)
{ m=i.m;
n=i.n; }};
#include<iostream.h>
Class complex Void display(complex d)
{ float real,imag; { cout<<c.real<<“+j”<<c.imag;
public: }
complex(){ } Int main()
complex(float x) {
{ real=imag=x;} complex a(3.4,6.7);
complex(float c, float d) complexb(2.5);
{ real=c; imag = complex c;
d; } c= sum(a,b);
friend complex sum cou<<“a=”;display(a);
(complex,complex);
cout<<“b=”;display(b);
friend display(complex);
cout<<“c=”;display(c);
};
}
Complex sum (complex c1, complex c2)
{ complex c3;
c3.real =c1.real +c2.real;
c3.imag=c1.imag+c2.imag;
Return(c3);
}
 Constructors are also define with default
arguments

 Complex (float real ,float imag=0);

 It will invoke by following way complex c(5),


this statement assign 5 to real and the default
value already assigned to imag.

 We can also invoke it like complex(5,3.4),it will


assign values both real and imag means
overwrite the new value to imag value.
Dynamic initialization of objects
 Objects can be initialized dynamically,initial
value of objects are provided during run
time.

 Advantage of it we can provide various


initialization formats by constructor
overloading.
Fixed_deposit :: fixed_deposit(long int p, int
#include<iostream.h> y1,int r1)
Class fixed_deposit { pamount=p;
{ y=y1;
long int pamount; r=r1;
int y; rvalue=pamount;
float r; for(int i=1;i<=y1;i++)
float rvalue; rvalue =rvalue*(1+float(r)/100);}
Public: Void fixed_deposit :: display()
fixed_deposit() { } {
fixed_deposit(long int p,int y1,float r1=0.2); cout<<“\n”
fixed_deposit(long int p,int y1, int r1); << “pricipal amount”<<pamount<<“\n”
void display(); <<“return value”<<rvalue<<“\n”;
}; }
Fixed_deposit :: fixed_deposit(long int p,int y1, Int main()
float r1) {
{ pamount =p; fixed_deposit fd1,fd2,fd3;
y=y1; long int p;int y1; float r; int R;
r=r1; Cout<<“enter amount,period,intrest rate in
rvalue=(pamount*y*r) ; percent”<<“\n”;
Rvalue=rvalue/100; Cin>>p>>y>>R;
} Fd1=fixed_deposit(p,y,R);
Cout<<“enter amount,period,intrest rate in
decimal ”<<“\n”;
Cin>>p>>y>>r;
Fd2=fixed_deposit(p,y,r);
Cout<<“enter amount and peroid”<<“\n”;
Cin>>p>>y;
Fd3=fixed_deposit(p,y);
Cout<<“\ndeposit 1”;
Fd1.display();
Cout<<“\n deposit 2”;
Fd2.display();
Cout<<“\n deposit 3”;
Fd3.display();
Return 0;
}
Destructors
 A destructor is used to destroy the objects that
have been created by constructor.
 It is also a member function of class whose
name same as class name but preceded by tiled
sign(~).
 It never takes any arguments nor return any
value.
 It will be invoked implicitly by the compiler
upon exit from the program to clean up the
storage which is allocated
 The new operator is used in constructor to
allocate memory and delete is used to free in
destructors.

 Expl:- ~assign()
 {
 Delete p;
}
#include<iostream.h> int main()
Int count =0; {
Class try cout<< “enter main”;
{ public: try t1,t2,t3,t4;
try() {
{ cout<<“block1”;
count++; try t5;
Cout<<“no of objects created”<<count; }
} {
~try() cout<<“block 2”;
{ try t6;
cout<<“no of object destroyed”<<count; }
Count- -; cout<<“again in main”;
}}; Return 0;
}

You might also like