Final UNIT-2 - C++
Final UNIT-2 - C++
BSc CS, IT, CT, SS, CSA, MM & B.C.A (Regular) –II SEMESTER
CORE 3: C++ PROGRAMMING
UNIT-2
Staff Name: S. Ganeshmoorthy MCA., M.Phil., MBA (Ph.D.)
-----------------------------------------------------------------------------------------------------------------------------------------
UNIT II: Classes and Objects: Declaring Objects – Defining Member Functions – Static Member
variables and functions – array of objects –friend functions – Overloading member functions – Bit
fields and classes – Constructor and destructor with static members.
------------------------------------------------------------------------------------------------------------------------------
Classes and Objects
Synopsis
1. Introduction
2. Definition of class
3. Class declaration
4. Explanation about class declaration
5. Members
6. Data Members
7. Encapsulation
8. Example program for class
9. Representation of Class
10. Access specifier in a class
Public
Private
Protected
Introduction
The important feature of C++ is “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 data members and function are called as member functions
A class is an extension of the idea of structure used in C.
It is a new way of creating and implementing a user defined data type.
Definition of class:
“A class is grouping of objects having identical properties, common behavior & shared relationship.”
Specifying a Class
A Class is a way to bind(fix) the data and its associated function together
It allows the data and function to be hidden from external use.
A group of object is called class
Object is real world run time entity
It may be any living or non living things
It consist of attributes and methods
Attributes=> characteristics or behaviour
Methods=> Fuctionality
1
Class declaration
Class classname
{
Private:
Variable declarations;
Private section
Function declarations;
(members)
Public: Access specifier
Variable declarations;
Function declarations; Public section
}; (members)
Representation of Class
2
Members
Members => The collection of functions and variables are said to be members
The members are denoted as two ways
Private
Public
Data members
The variables declared inside the class are known as data members
The functions are known as member functions
Only member functions can have access to private data members and private function
Encapsulation
The binding or wrapping or packaging or covering of data and functions together into a single
class type variable is referred to as encapsulation
Public Keyword:
The member variables and the member functions declared in the public section can be
directly accessed with the help of object.
Public keyword is terminated by a colon (:)
Private Keyword:
3
The member variables and the member functions declared in the Private section cannot be
directly accessed with the help of object.
The private keyword is used to prevent direct access of member variables and functions.
Private keyword is terminated by a colon (:)
Protected Keyword:
The protected keyword has the same effect as the private.
The protected keyword is used in the inheritance of classes.
Protected keyword is terminated by a colon (:)
Declaring objects
Synopsis
1. Introduction
2. Definition of class
3. State identity and behavior of objects
4. Syntax for creating object
5. Example for creating object
6. Accessing class Members
7. Formats for calling a member function
8. Example
Introductin
Once a class (ITEM) has been created , we can create variable of that type (class type) by using
following syntax which is called object
Definition of Object
Object is real world run time entity
Entity is an real world object
It may be any living or non living things
It consist of attributes and methods
Attributes=> characteristics or behaviour
Methods=> Fuctionality
An object is an instance of a class.
An object is a class variable.
Is can be uniquely identified by its name.
Every object has a state which is represented by the values of its attributes.
These state are changed by function which applied on the object
Class Classname
{
…….
}object name
4
Or
Class_name Object_name
Class Student
{
…..
}s1,s2;
Or
Student s1;
} x,y,z;
The object can access only the public member variables and member functions of a class by
using operator dot (.) and arrow (->)
The syntax is as follows,
The private data of a class can be accessed only through the member functions of that class.
The main ( ) cannot contain statements that access number and cost directly.
Example:
5
x.getdata(100, 75.5);
In the above example the value 100 is the number and 75.5 is the cost of an object x by
implementing getdata( ) function.
Similarly, the statement
X.putdata( );
In above function it send a message to the object x requesting to display its contents
A variable declared as public can be accessed by objects directly
Class xyz
{
Int x;
Int y;
Public
Int z;
};
….
….
Xyz p;
p.x=0; //error, x is private
p.z=10 //OK, z is pubic
….
….
Synopsis
1. Introduction
a. Inside the class definition
b. Outside the class definition
2. Private member function
Introduction
A member function can be defined in two places in the class
It can be defined in 2 places
o Inside the class definition
o Outside the class definition
Class item
{
Int number;
Float cost;
Public:
Void getdata(int a, float b); //declaration
//inline function
Void putdata (void); //definition
6
{
Cout <<number<<”\n”;
Cout<<cost<<”\n”;
}
};
When a function is defined inside a class, it is treated as an inline function
The membership label classname:: tells the compiler that the function function-name belongs to
the class classname
The scope of the function is restricted to the class-name specified in the header line.
The symbol ::=>scope resolution operator
Example
Void item::getdata(int a, float b) //getdata =>member functions
{
Number =a;
Cost=b;
}
Void item::putdata(void) // putdata =>member functions
{
Cout<<”number:”<<number<<”\n”;
Cout<<”cost:”<<cost<<”\n”;
}
7
2. Only one copy of that member is created for entire class and shared by all objects of that class, no
matter how many objects are created.
3. It is visible only within a class, but its life time is the entire program.
#include<iostream>
using namespace std;
class student{
int roll_no;
char name[15];
static char course[15]; // Static member Variables
public:
void getdata() {
cout<<" Enter roll number:";
cin>>roll_no;
cout<<" Enter Name:";
cin>>name;
}
void putdata() {
cout<<"Student Roll Number: "<<roll_no<<"\n";
cout<<"Student Name: " <<name<<"\n";
cout<<"Student Class: " <<course<<"\n";
}
};
char student::course[15]="BCA";
int main()
{
int n;
cout<<"Enter number of student you want...";
cin>>n;
student s[n]; // array of object
for(int i=0;i<n;i++)
{
cout<<"Detail of student"<<i+1<<"\n";
s[i].getdata();
}
cout<<"\n";
for(int i=0;i<n;i++)
{
cout<<"\n\nStudent"<<i+1<<"\n";
cout<<"--------\n";
s[i].putdata();
}
return 0;
}
8
Output:
Introduction
A member function that is declared static has the following properties
A static function can have access to only other static members (function or variable) declared in
same class
A static member function can be called using the class name as follows
Class-name:: function-name
9
}
static void showcount() // Static member functions
{
cout<<"\ncount object is:"<<count;
}
};
int stat_fun::count;
int main()
{
stat_fun o1,o2;
o1.stat();
o1.stat();
stat_fun::showcount();
stat_fun o3;
o3.stat();
stat_fun::showcount();
return 0;
}
Output:
Arrays of object
Synopsis
1. Introduction
2. Syntax for Array of Object
3. Example
4. For Example using class:
5. Example Program Using Array of Pointers
6. Output
Introduction 7. Explanation about array of pointers
Arrays are collection of similar data types.
We know that an array can be of any data type including Struct.
Similarly, we can also have arrays of variables that are of the type class.
Such variables are called arrays of objects.
Example:
Student s [size];
10
Float per;
Public:
int regno, age;
Void getdata ( );
Void show ( );
};
For this class if we required 100 student, then we are not declare different s1,s2,…,s100 object
because it’s very critical task.
For this problem we use array of object.
#include<iostream.h>
Using namespace std;
Class student
{
Char name [15];
Float age;
Public:
Void getdata ();
Void putdata ();
};
Void student:: getdata()
{
cout<<"Enter Name: ";
cin>>name;
cout<<"Enter Age: ";
cin>>age;
}
Void student:: putdata()
{
cout<<"Name: "<<name<<"\n";
cout<<"Age: "<<age <<"\n";
}
const int size=2;
int main()
{
student s[size]; // array of object
for(int i=0;i<size;i++)
{
cout<<"Detail of student"<<i+1<<"\n";
s[i].getdata();
}
cout<<"\n";
for(int i=0;i<size;i++)
{
cout<<"\n\nStudent"<<i+1<<"\n";
cout<<"--------\n";
s[i].putdata();
}
return 0;
}
11
Output:
Example
Employee manager [3]; //array of manager
Employee foreman [15]; //array of foreman
Employee worker [75]; //array of worker
In the above example, the array manager contains three objects (managers) namely
Manager [0]
Manager [1]
Manager [2]
of type employee class
In the above example, the array foreman contains 15 objects (foreman) namely
Foreman [0]……. Foreman [14]
of type employee class
In the above example, the array worker contains 75 objects (worker) namely
Worker [0]……. Worker [74]
of type employee class
The following statement helps to display the elements of array of objects
Manager[i].putdata( );
The above statement requests the object manager[i] to invoke the member function putdata
Friend function
Synopsis
1. 1.Introduction
2. Syntax of Friend function
3. Example of Friend function
4. Declaration of Friend function
5. Characteristic of friend function
6. Program using friend function
7. Output
8. Advantage of having friend function
9. Disadvantage of having friend function
Introduction
The functions that are declared with the keyword friend are known as Friend functions
12
A function can be declared as a friend in any number of classes
The function declaration should be preceded by the keyword friend
The function is defined elsewhere in the program like a normal C++ function.
C++ allows a mechanism, in which a non-member function has access permissions to the
private member of the class.
This can be done by declaring the non-member function “friend‟ to the class whose private data
is to be accessed.
For example, consider a two classes, manager and scientist have been defined.
We would like to use a function income_tax() to operate on the objects of both these classes,
thereby allowing the function to have access to the private data of these classes.
#include<iostream.h>
#include<conio.h>
Class acc
{
Private:
Char name[20];
13
int accno;
Float bal;
Public:
Void read ( )
{
cout<<”name:”;
cin>>name;
cout<<”a/c no:”;
cin>>accno;
cout<<”balance:”;
cin>>bal;
}
Friend void showbal(acc); //friend function declaration
};
Void showbal( acc a)
{
cout<<”Balance of acc no.”<<a.accno<<” ”is Rs.”<<a.bal;
}
Void main ( )
{
acc k;
k.read( );
showbal(k);
}
In this pgm,”showbal( )‟ is the non-member function that has the access over the private
member i.e., ‟name‟, “accno‟, “bal‟ of the class
Just because it has been declared as friend to the class.
Access to private member is possible.
Introduction
It have two or more functions can have same name but different parameters
It is otherwise known as function Overloading.
14
Definition of function overloading
The process of using same functions name to create functions that perform a variety of
different task is called FUNCTION OVERLOADING.
The function is based on the following ways
o Different argument –[void add(int a); void add(float a);]
o Different no of argument–[ void add(int a); void add(float a,float b);]
o Different function type-[int disp(), char disp()]
For eg: add( ) function handles different types of data as shown in below
If two or more function having same name but different arguments are known as function
overloading
//Function calls
#include<iostream.h>
Using namespace std
15
Output:
The Integer number is: 10
The floating number is: 10.10
The Char* is: ten
Bit fields and classes
Synopsis
1. Introduction
2. Example
3. Memory size for each data type
4. Advantage of using bit fields
Introduction
Bit field provides exact amount of bits required for storage of values.
If variable value is 1 or 0 then a single bit is enough to store it.
If variable value is 0 or 3 then a 2 bits are enough to store it.
If variable value is 0 or 7 then a 3 bits are enough to store it.
The number of bits required for a variable is specified by non-negative integer followed by
colon.
Example;
Class vehicle
{
Unsigned type: 3;
Unsigned fuel: 2;
Unsigned model: 3;
}
16
Class vehicle
{
Private:
Unsigned type: 3;
Unsigned fuel: 2; 0
Unsigned model: 3;
Public:
vechicle( )
{
Type= FOUR_WH;
Fuel= PETROL;
Model=NEW;
}
Void show( )
{
if (model==NEW)
cout<<„„\n New model”;
else
cout<<„„\n Old model”;
cout<<„„Type of vehicle: ”<<type;
cout<<„„Fuel: ”<<fuel;
}
};
void main( )
{
vehicle v;
cout<<„„size of object:”<<sizeof(v);
v.show( );
}
Output:
Size of object: 1
New model
Type of vehicle: 4
Fuel: 1
17
Introduction
Constructor constructs the objects and destructor destroys the objects.
The compiler automatically executes these functions.
Constructor is executed when the object is created and destructor is executed at the end of the
function when object goes out of the scope.
Constructor
A constructor is a special member function.
Constructor has the same name as that of the class name.
Constructor is used to construct the objects.
Declaration of Constructor
18
Explicit call of Constructor
Features of constructor
Constructor has the same name as class
It does not have any return type not even void
Constructor can be declared only in public section of the class
Constructor is called automatically when the object of the class is created
Functions of constructor
1. The constructor function initializes the class object
2. The memory space is allocated to the object
Types of Constructor
There are three types of Constructor.
They are
1. Default constructor
2. Parameterized constructor
3. Copy constructor
Default constructor
A constructor that accepts no parameter is called the default constructor
It have no argument
It is used to initialize an object of a class with legal initial values
Example program
Class student //class
{
Private:
Int rollno;
19
Float marks;
Public:
Student( ) //Constructor
{
rollno=0;
marks=0.0
}
Void display ( );
Void enter ( );
};
Void main()
{
Student s1; //default constructor called
}
Parameterized constructor
Example program
Class student //class
{
Private:
Int rollno;
Char name[20];
Float marks;
Public:
Student ( ) //Constructor
//default constructor
{
rollno=0;
marks=0.0
}
Student (Int roll, char nam[20],float mar)
//parameterized constructor
{
Rollno=roll;
Strcpy(name, nam);
Marks=mar;
}
Void display ( );
Void enter( );
20
};
Void main ( )
{
Student s1;
Student s2 (1,”ramesh”, 350);
Student s3=student (2,”kajal”, 400);
}
Copy constructor
It is a special constructor in the C++ programming language
It is used to create a new object as a copy of an existing object
It accepts an objects as an argument
It creates a new object and initializes its data members with data members of the object passed
to it as an argument
Syntax
Example program:
Class student //class
{
Private:
Int rollno;
Char name[20];
Float marks;
Public:
Student ( ) //Constructor
//default constructor
{
rollno=0;
marks=0.0
}
Student (Int roll, char nam[20],float mar)
//parameterized constructor
{
Rollno=roll;
Strcpy(name, nam);
Marks=mar;
}
Student (student &s) //copy constructor
{
Rollno=s.rollno;
Strcpy(name, s.name);
Marks=s.marks;
}
}
Void main ( )
{
Student s1; //statement1
21
Student s2 (1,”ramesh”, 350); //statement2
Student s3(S2); //statement3
Student s4 (2,”Kajal”, 320); //statement4
Student s5=s4; //statement5
}
Constructor overloading
C++ allows more than one constructors to be defined in a single class
Defined more than one constructors in a single class provided they all differ in either type or
number of argument is called constructor overloading
Example program:
Class student //class
{
Private:
Int rollno;
Char name[20];
Float marks;
Public:
Student ( ) //default constructor
{
rollno=0;
marks=0.0
}
Student (Int roll, char nam[20],float mar) //parameterized constructor =>1
{
Rollno=roll;
Strcpy(name, nam);
Marks=mar;
}
Student (Int roll, char nam[20]) // parameterized constructor=>2
{
Rollno=roll;
Strcpy(name, nam);
Marks=100;
Defining more than one constructor in a single class is called constructor overloading
We can define as many parameterized constructors as we want in a single class provided they
all differ in either number or type of arguments
22
Dynamic constructor
The constructors can also be used to allocate memory while creating objects.
This will enable the system to allocate the right amount of memory 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 of objects.
The memory is created with the help of the new operator.
Destructor
A destructor is a special member function
Destructors are opposite to constructor.
The process of destroying the class objects created by constructor is done in destructor.
The destructor has the same name as the class name, preceded by a tilde (~).
A destructor is automatically executed when the object goes out of the scope.
A class should have only one destructor.
Declaration of Destructor
~ class name
Example program:
#include<iostream.h>
Class student
{
Public:
Student ( )
{
cout<<”Constructor called”;
}
~student ( )
{
cout<<”Destructor called”;
}
};
Void main ( )
{
clrscr( );
Student s;
}
OUTPUT:
Constructor called
Destructor called
Features of Destructor
It has the same as that of class and preceded by tilde sign(~)
It is automatically by the compiler when an object goes out of scope
Destructors are used to deallocate memory
It performs other cleanup for a class object and its class members when the object is destroyed.
It always declared in the public section of the class
We have only one destructor in a class
23
Rules for destructor definition and usage
The destructor has the same name as that of the class prefixed by the tilde character
The destructor cannot have arguments
It has no return type
Destructors cannot be overloaded i.e., there can be only one destructor in class
In the absence of user defined destructor, it is generated by the compiler
The destructor is executed automatically when the control reaches the end of class scope
24