SlideShare a Scribd company logo
1 of 150
Download to read offline
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
1
C Structure Revisited
We known that one of the unique feature of the C language is structures.
They provide a method for packing together data of different types.
A structure is a convenient tool for handling a group of logically related data items.
It is a user define data type with a template that serves to define its data properties.
Once the structure type has been defined, we can create variables of that type using declaration that are
similar to the built in type declaration.For example, consider the following declaration:
struct student
{
char name[20];
int roll_number;
float total_marks;
};
The keyword struct declare student as a new data type that can hold three fields of different data types.
These fields are known as structure member or elements.
The identifier student, which is referred to as structure name or structure tag, can be used to create
variables of type student.
Example:
struct student A; // C declaration
A is a variable of type student and has three member variables as defined by the template. Member
variable can be accessed using the dot or period operator as follows:
strcpy(A.name, "John");
A.roll_number = 999;
A.total_marks = 595.5;
final_total = A.total_marks + 5;
Structure can have arrays, pointer or structure as members.
Limitations of structure:
Important limitation of structures is that they do not permit data hiding.
The only difference between a structure and a class in C++ is that, by default, the members of a class are
private while, by default, the members of structures are public.
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
2
Specifying a class:
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 build-in data type.
Generally, a class specification has two parts:
1. Class declaration
2. Class function definitions
The class declaration describes the type scope of its members.
The class function definitions describe how the class functions are implemented.
The general form of a class declaration is:
class class_name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};
More about Classes
Classes contain data members and member functions, and the access of these data members and variable
depends on the access specifiers.
Class's member functions can be defined inside the class definition or outside the class definition.
Class in C++ is similar to structures in C, the only difference being, class defaults to private access
control, where as structure defaults to public.
All the features of OOPS, revolve around classes in C++. Inheritance, Encapsulation, Abstraction etc.
Objects of class holds separate copies of data members. We can create as many objects of a class as we
need.
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
3
Objects
Class is a blueprint or a template.
No storage is assigned when we define a class. Objects are instances of class, which holds the data
variables declared in class and the member functions work on these class objects.
class Abc
{
int x;
void display(){} //empty function
};
int main()
{
Abc obj; // Object of class Abc created
}
Access Control in Classes:
Now before studying how to define class and its objects, lets first quickly learn what are access specifiers.
Access specifiers in C++ class define the access control rules. C++ has 3 new keywords introduced, namely,
public
private
protected
• These access specifiers are used to set boundaries for availability of members of class be it data members
or member functions
• Access specifiers in the program, are followed by a colon. You can use either one, two or all 3 specifiers
in the same class to set different boundaries for different class members. They change the boundary for all
the declarations that follow them.
Public
Public, means all the class members declared under public will be available to everyone. The data
members and member functions declared public can be accessed by other classes too. Hence there are chances
that they might change them. So the key members must not be declared public.
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
4
class PublicAccess
{
public: // public access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}
Private
Private keyword, means that no one can access the class members declared private outside that class. If
someone tries to access the private member, they will get a compile time error. By default class variables and
member functions are private.
class PrivateAccess
{
private: // private access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}
Protected
Protected, is the last access specifier, and it is similar to private, it makes class member inaccessible
outside the class. But they can be accessed by any subclass of that class.
class ProtectedAccess
{
protected: // protected access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}
Defining Class and Declaring Objects
When we define any class, we are not defining any data, we just define a structure or a blueprint, as to what the
object of that class type will contain and what operations can be performed on that object.
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
5
Below is the syntax of class definition,
class ClassName
{
Access specifier:
Data members;
Member Functions(){}
};
Here is an example, we have made a simple class named Student with appropriate members,
class student
{
public:
int rollno;
string name;
};
So its clear from the syntax and example, class definition starts with the keyword "class" followed by the class
name. Then inside the curly braces comes the class body, that is data members and member functions, whose
access is bounded by access specifier. A class definition ends with a semicolon, or with a list of object
declarations.
Example :
class student
{
public:
int rollno;
string name;
}A,B;
Here A and B are the objects of class Student, declared with the class definition. We can also declare objects
separately, like we declare variable of primitive data types. In this case the data type is the class name, and
variable is the object.
int main()
{
student A;
student B;
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
6
}
Both A and B will have their own copies of data members.
Simple Class Program:
// Header Files
#include <iostream>
#include<conio.h>
// Class Declaration
class person
{
//Access - Specifier
public:
//Varibale Declaration
char name[20];
int number;
};
//Main Function
void main()
{
// Object Creation For Class
person obj;
//Get Input Values For Object Varibales
cout<<"Enter the Name :";
cin>>obj.name;
cout<<"Enter the Number :";
cin>>obj.number;
//Show the Output
cout << obj.name << ": " << obj.number << endl;
getch();
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
7
Sample Output:
Enter the Name :Riya
Enter the Number :100
Riya: 100
Defining Member Functions in Classes
Member functions are the functions, which have their declaration inside the class definition and works on
the data members of the class.
The definition of member functions can be inside or outside the definition of class.
If the member function is defined inside the class definition it can be defined directly, but if its defined
outside the class, then we have to use the scope resolution :: operator along with class name along with
function name.
If we define the function inside class then we don't not need to declare it first, we can directly define the function.
Inside the class definition:
class Cube
{
public:
int side;
int getVolume()
{
return side*side*side; //returns volume of cube
}
};
But if we plan to define the member function outside the class definition then we must declare the function inside
class definition and then define it outside.
outside the class definition:
class Cube
{
public:
int side;
int getVolume();
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
8
int Cube :: getVolume() // defined outside class definition
{
return side*side*side;
}
The main function for both the function definition will be same. Inside main() we will create object of class, and
will call the member function using dot . operator.
void main()
{
Cube C1;
C1.side=4; // setting side value
cout<< "Volume of cube C1 ="<< C1.getVolume();
}
Making an Outside Function Inline
One of the objectives of OOP is to separate the details of implementation from the class definition. It is
therefore good practice to define the member functions outside the class.
We can define a member function outside the class definition and still make it inline by just using the
qualifier inline in the header line of the function definition.
Example:
class item
{
......
......
public:
void getdata(int a,float b);
};
inline void item :: getdata(int a,float b)
{
number=a;
cost=b;
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
9
Nesting of Member Functions
A member function of a class can be called only by an object of that class using a dot operator.
However, there is an exception to this. A member function can be called by using its name inside another
member function of the same class. This is known as nesting of member functions.
Nesting of Member Function
#include <iostream.h>
#include<conio.h>
class set
{
int m,n;
public:
void input();
void display();
int largest();
};
int set :: largest(void)
{
if(m >= n)
return(m);
else
return(n);
}
void set :: input(void)
{
cout << "Input value of m and n"<<"n";
cin >> m>>n;
}
void set :: display(void)
{
cout << "largest value=" << largest() <<"n";
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
10
int main()
{
set A;
A.input();
A.display();
return 0;
}
The output of program would be:
Input value of m and n
25 18
Largest value=25
Private Member Functions
Although it is normal practice to place all the data items in a private section and all the function in public,
some situations may require certain function to be hidden from the outside calls. Tasks such a deleting an
account in a customer file, or providing increment to an employee are event of serious consequences and
therefore the function handling such task should have restricted access. We can place these function in the
private section.
A private member function can only be called by another function that is a member of its class. Even an
object cannot invoke a private function using the dot operator. Consider a class as defined below:
class sample
{
int m;
void read(void);
public:
void update(void);
void write(void);
};
if s1 is an object of sample, then
s1.read (); // won’t work, objects cannot access private members
However, the function read() can be called by the function update() to update the value of m.
void sample :: update(void)
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
11
{
read(); // simple call; no objects used
}
Arrays within a Class
An array is a user defined data type whose members are homogeneous
Arrays are used to store huge volume of similar data types.
arrays can be easily manipulated with the help of loops
it can used as member variables in a class
Example:
#include<iostream.h>
#include<conio.h>
class student
{
int regno;
float mark[4], total;
char name[20];
public:
void getdetails();
void displaydetails();
};
void student ::getdetails()
{
cout<<"Enter the name";
cin>>name;
cout<<"Enter the Register number";
cin>>regno;;
cout<<"Enter 4 marks one by one"<<endl;
for(int i=0;i<4;i++)
{
cin>>mark[i];
total=total+mark[i];
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
12
}
void student :: displaydetails()
{
cout<<"STUDENT DETAILS n";
cout<<" Name :"<<name<<endl;
cout<<" Register Number"<<regno<<endl;
for(int i=0;i<4;i++)
{
cout<<"Mark"<<i+1<<"="<<mark[i]<<endl;
cout<<"Total"<<total;
}
}
void main()
{
clrscr();
student s1;
s1.getdetails();
s1.displaydetails();
getch();
}
Run
Enter the name : Riya
Enter the Register number : 35
Enter 4 marks one by one :
78
80
99
89
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
13
Output
STUDENT DETAILS
Name : Riya
Register number : 35
Mark 1 = 78
Mark 2 = 80
Mark 3 = 99
Mark 4 = 89
Total = 346
Memory allocation for objects
When a class is declared, memory is not allocated to data members of the class.
Thus, there exists a template, but data members cannot be manipulated unless the object is created.
It is note that when an object of a particular class is created, memory is allocated to both of its data
members and member function. This is partially true.
When an object is created, memory is allocated only to its data members and not to member function.
The member function are created and placed in the memory only once when they are defined in the class
specifier.
The member functions are the same for all objects, no separate space is allocated member functions when
objects are created.
However separate storage is allocated for each objects data member since they contain different values.
The following figure illustrated the idea the objects contains separate memory
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
14
Static data members:
The static data members are data objects that are common to all the objects of a class.
Characteristics:
• It is initialized to 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.
Object 2
Data 1
Data 2
.
.
Data m
Object 3
Data 1
Data 2
.
.
Data m
Object 1
Data 1
Data 2
.
.
Data m
Function1()
Function2()
Function 3()
.
.
Function n()
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
15
Syntax:
Class classname
{
……………………
Static datatype datamember;
…………………….
};
Datatype classname :: datamember=initial value
Example :
static int count;
int item :: count;
Static variables are normally used to maintain values common to the entire class. For example, a static data
membevor can be used as a counter that records the occurrences of all the objects. Program illustrates the use of a
static data member.
#include <iostream.h>
#include<conio.h>
class item
{
static int count;
int number;
public:
void getdata(int a)
{
number = a;
count ++;
}
void getcount(void)
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
16
{
cout << "Count: ";
cout << count <<"n";
}
};
int item :: count;
void main()
{
item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout << "After rea.gading data"<<"n";
a.getcount();
b.getcount();
c.getcount();
getch();
}
The output of the program would be:
Count: 0
Count: 0
Count: 0
After reading data
Count: 3
Count: 3
Count: 3
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
17
Static Member Functions
Like static member variable, we can also have static member function. A member function that is declared static
has the following properties:
• A static function can have access to only static members declared in the class.
• A static member function can be called the class name as follows:
class-name :: function-name;
#include<iostream.h>
#include<conio.h>
class test
{
int code;
static int count;
public :
void setcode(void)
{
code= ++count;
}
void showcode(void)
{
cout<<"object number"<<code<<endl;
}
static void showcount(void)
{
cout<<"count"<<count<<endl;
}
};
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
18
int test::count;
void main()
{
clrscr();
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount();
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
getch();
}
OUTPUT
Count 2
Count 3
Object number 1
Object number 2
Object number 3
Arrays of objects :
C++ allows to create an array of any data type including user defined data types
Thus an array of variables that are of the type class can also be defined. Such variables are called
arrays of an objects.
It is often used to handle group of object which reside contiguously in the memory.
Syntax:
Classname arrayname[size of the array]
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
19
Conceptual Explanation:
Consider the following class definition
Class employee
{
Char name[30];
Float age;
Public:
Void getdata();
Void putdata();
};
The identifier employee is a user defined data type and can be used to create objects that releate to
different categories of the employees for example
employee manager[3];
employee foreman[15];
the array manager contains three objects (managers), namely,manager[0], manager[1] and manager[2], of type
employee class. Similarly, the foreman array contains 15 objects (foreman).
Example Program :
#include<iostream.h>
#include<conio.h>
class rec
{
private:
int i;
int b;
public:
rec(int a,int c)
{
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
20
i=a;
b=c;
}
void put()
{
cout<<"Area is : "<<i*b <<endl;
}
};
void main()
{
clrscr();
rec obj[3]={rec(3,6),rec(2,5),rec(5,5)};
cout<<"Displaying Areas of Rectangles : n";
for(int i=0;i<3;i++)
obj[i].put();
getch();
}
Objects as function Arguments :
• Objects can be used as function arguments, by these arguments we can pass either the values of the object
or address of the object.
• An object can be used as a function argument by the following way
A copy of the entire object is passed to the function
Only the address of the object is transferred to the function
Pass-by-value:
The first method is called pass-by-value
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
21
Since 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 the function.
Pass-by-reference:
The second method is called Pass-by-reference
When address of the object is passed, the called function works directly on the actual object used
in the call
This means any changes made to the object inside the function will reflect the actual object.
The pass by reference method is more efficient since it requires to pass only the address of the
object and not the entire object.
Syntax :
If the function has no return value, the syntax is
functionname(argument list);
If the function has return value, the syntax is
Objectname. functionname(argument list);
Or
Objectname=functionname(argument list);
Example :
#include<iostream.h>
#include<conio.h>
class time
{
int hours;
int minutes;
public :
void gettime(int h,int m)
{
hours=h;
minutes=m;
}
void puttime()
{
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
22
cout<<hours<<"hours and";
cout<<minutes<<"minutes"<''n";
}
void sum(time,time);
};
void time :: sum (time t1, time t2)
{
minutes=t1.minutes+t2.minutes;
hours=minutes/60;
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
}
void main()
{
tiem t1,t2,t3;
t1.gettime(2,45);
t2.gettime(3,30);
t3.sum(t1,t2);
cout<<"t1=";t1.puttime();
cout<<"t2=";t2.puttime();
cout<<"t3=";t3.puttime();
getch();
}
output:
t1=2 hours and 45 minutes
t1=3 hours and 30 minutes
t1=6 hours and 15 minutes
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
23
Friendly Functions:
The main concept of object oriented programming are data hiding and data encapsulation.
Whenever data objects are declared in a private or protected category of class, these members are
restricted by accessing by non member function
To solve this problem, a friend function can be declared to have an access these members
The friend function is a non member function that allows the function to access private data
One of the most common reason for using this function is to access two separate classes
Syntax:
Class classname
{
Private:
…………….
…………….
Public:
…………….
…………….
Friend return type nonmemberfunction name(argument list);
};
Rules:
The keyword friend can be used only inside the class
More than one friend function can be declared in a class
A function can be friend to more than one classes
The friend function definition should not contain the scope operator
#include<iostream.h>
#include<conio.h>
class base
{
int val1,val2;
public:
void get()
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
24
{
cout<<"Enter two values:";
cin>>val1>>val2;
}
friend float mean(base ob);
};
float mean(base ob)
{
return float(ob.val1+ob.val2)/2;
}
void main()
{
clrscr();
base obj;
obj.get();
cout<<"n Mean value is : "<<mean(obj);
getch();
}
Output:
Enter two values: 10, 20
Mean Value is: 15
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
25
Returning Objects:
A function not only receive object as arguments but also can return them
If a member function called by an object returns an object then it is called function returning objects
The syntax used is similar to that of returning variables from function
The return type of function is declared as the return object type
Program :
#include<iostream.h>
#include<conio.h>
class complex
{
float x;
float y;
public :
void input(float real, float imag)
{
x=real;
y=imag;
}
friend complex sum(complex,complex);
void show(complex);
};
complex sum(complex c1,complex c2)
{
complex c3;
c3.x=c1.x+c2.x;
c3.y=c1.y+c2.y;
return(c3);
}
void complex :: show(complex c)
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
26
{
cout<<c.x<<"+j"<<c.y<<"n";
}
void main()
{
complex a,b,c;
a.input(3.1,5.65);
b.input(2.75,1.2);
c=sum(a,b)
cout<<"a=";a.show(a);
cout<<"b=";b.show(b);
cout<<"c=";c.show(c);
getch();
}
Output:
a=3.1+j5.65
b=2.75+j1.2
c=5.85+j6.85
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
27
Important points in unit I :
A class is an extension to the structure data type
A class can have both variables and functions as members
By default members of the class are private whereas that of structure are public
Only the member functions can have access to the private data members and private functions. However
the public members can accessed from the outside the class
In c++, the class variables are called object. With objects we can access the public members of a class
using dot(.) operator
We can define a member function inside or outside the class.
The difference between a member function and a normal function is that a member function uses a
membership ‘identity label’ in the header to indicate the class to which it belongs.
The memory space for objects is allocated when they are declared
Space for member variables is allocated separately for each object, but no separate space is allocated for
member functions
A data members of a class can declared as a static and is normally used to maintain values comman to the
entire class
The static member variable must be defined outside the class
A static member function can have access to the static members declared in the same class and be called
using the class name
A function is declared as a friend is not in the scope of the class to which it has been declared as friend. It
has full access to the private members of the class
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
28
UNIT II
Constructor:-
Constructor is used for initializing the values to the data members of the Class.
Constructor is that whose name is same as name of class.
Constructor gets automatically called when an object of class is created.
Constructors never have a Return Type even void.
Constructor are of
o Default ,
o Parameterized and
o Copy Constructors
Syntax:
class A
{
int x;
public:
A(); //Constructor
};
While defining a constructor you must remember that the name of constructor will be same as the name of
the class, and constructors never have return type.
Constructors can be defined either inside the class definition or outside class definition using class name
and scope resolution:: operator.
class A
{
int i;
public:
A(); //Constructor declared
};
A::A() // Constructor definition
{
i=1;
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
29
}
Characteristics of Constructors
They should be declared in the public section
They are automatically invoked and have no return types, neither can they return values
They can not be inherited but called by Derived Class Constructor
They can not be virtual nor can we refer to their addresses & they can have default arguments
An object with constructor or destructor can’t member of union
They make implicit calls to new and delete
When constructor is declared, init becomes mandatory
Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no parameter.
Syntax :
class_name ()
{
Constructor Definition
}
Example :
class Cube
{
int side;
public:
Cube()
{
side=10;
}
};
int main()
{
Cube c;
cout << c.side;
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
30
Output : 10
In this case, as soon as the object is created the constructor is called which initializes its data members.
A default constructor is so important for initialization of object members, that even if we do not define a
constructor explicitly, the compiler will provide a default constructor implicitly.
class Cube
{
int side;
};
int main()
{
Cube c;
cout << c.side;
}
Output : 0
In this case, default constructor provided by the compiler will be called which will initialize the object data
members to default value, that will be 0 in this case.
Example 2 : Default Constructor
#include<iostream>
#include<conio.h>
class Example
{
// Variable Declaration
int a,b;
public:
//Constructor
Example()
{
// Assign Values In Constructor
a=10;
b=20;
cout<<"Im Constructorn";
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
31
void Display()
{
cout<<"Values :"<<a<<"t"<<b;
}
};
Void main()
{
Example Object;
// Constructor invoked.
Object.Display();
// Wait For Output Screen
getch();
}
Sample Output
Im Constructor
Values :10 20
Parameterized Constructor
These are the constructors with parameter. Using this Constructor you can provide different values to data
members of different objects, by passing the appropriate values as argument.
Example :
class Cube
{
int side;
public:
Cube(int x)
{
side=x;
}
};
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
32
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
OUTPUT : 10 20 30
By using parameterized constructor in above case, we have initialized 3 objects with user defined values.
We can have any number of parameters in a constructor.
Example 2:
Definition
In C++,Constructor is automatically called when object(instance of class) create.It is special member
function of the class.Which constructor has arguments thats called Parameterized Constructor.
• It has same name of class.
• It must be a public member.
• No Return Values.
• Default constructors are called when constructors are not defined for the classes.
Syntax:
class class-name
{
Access Specifier:
Member-Variables
Member-Functions
public:
class-name(variables)
{
// Constructor code
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
33
... other Variables & Functions
}
Example Program
#include<iostream>
#include<conio.h>
class Example
{
// Variable Declaration
int a,b;
public:
//Constructor
Example(int x,int y)
{
// Assign Values In Constructor
a=x;
b=y;
cout<<"Im Constructorn";
}
void Display()
{
cout<<"Values :"<<a<<"t"<<b;
}
};
int main()
{
Example Object(10,20);
// Constructor invoked.
Object.Display();
// Wait For Output Screen
getch();
return 0;
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
34
Sample Output
In Constructor
Values :10 20
Multiple Constructor in a class : (Constructor Overloading)
Syntax
class class-name
{
Access Specifier:
Member-Variables
Member-Functions
public:
class-name()
{
// Constructor code
}
class-name(variables)
{
// Constructor code
}
... other Variables & Functions
}
Example Program
#include<iostream>
#include<conio.h>
class Example
{
// Variable Declaration
int a,b;
public:
//Constructor wuithout Argument
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
35
Example()
{
// Assign Values In Constructor
a=50;
b=100;
cout<<"nIm Constructor";
}
//Constructor with Argument
Example(int x,int y)
{
// Assign Values In Constructor
a=x;
b=y;
cout<<"nIm Constructor";
}
void Display()
{
cout<<"nValues :"<<a<<"t"<<b;
}
};
int main()
{
Example Object(10,20);
Example Object2;
// Constructor invoked.
Object.Display();
Object2.Display();
// Wait For Output Screen
getch();
return 0;
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
36
}
Sample Output
In Constructor
In Constructor
Values :10 20
Values :50 100
Dynamic Initialization of Objects
One Advantage Of Dynamic Initialization is that we can Provide Various initialization formats,
using Overloaded Constructors.
This Provides The Flexibility Of using different Formats of Data at run time Depending upon the
situation
//long-term fixed deposit system
#include<iostream.h>
class Fixed_deposit
{
long int P_amount; //principal amount
int Years; //Period of investment
float Rate; //Insert rate
float R_value; //Return value of amount
public:
Fixed_deposit(){}
Fixed_deposit(long int p, int y, float r=0.12);
Fixed_deposit(long int p, int y, int r);
void display(void);
};
Fixed_deposit :: Fixed_deposit(long int p, int y, float r)
{
P_amount = p;
Years = y;
Rate = r;
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
37
R_value = P_amount;
for(int i =1; i<=y; i++)
R_value = R_value * (1.0 + r);
}
Fixed_deposit :: Fixed_deposit(long int p, int y, int r)
{
P_amount = p;
Years = y;
Rate = r;
R_value = P_amount;
for(int i = 1; i<= y; i++)
R_value = R_value*(1.0+float(r)/100);
}
void Fixed_deposit :: display(void)
{
cout<<"n"
<<"Principal Amount = " <<P_amount <<"n"
<<"Return Value = " <<R_value <<"n";
}
int main()
{
Fixed_deposit FD1,FD2,FD3; //deposit created
long int p; //principal amount
int y; //investment period, years
float r; //interest rate, decimal form
int R; //interest rate, percent form
cout<< "Enter amount, peroid, interset rate(in precent)"<<"n";
cin >> p >> y >> R;
FD1 = Fixed_deposit(p,y,R);
cout<< "Enter amount, peroid, interset rate(in decimal form)"<<"n";
cin >> p >> y >> r;
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
38
FD2 = Fixed_deposit(p,y,r);
cout<< "Enter amount and period"<<"/n";
cin >> p >> y;
FD3 = Fixed_deposit(p,y);
cout <<"nDeposit 1";
FD1.display();
cout <<"nDeposit 2";
FD2.display();
cout<<"nDeposit 3";
FD3.display();
return 0;
}
Output:
Enter amount, period, interest rate (in percent)
10000 3 18
Enter amount, period, interest rate (in decimal form)
10000 3 0.18
Enter amount, period, interest rate (in percent)
10000 3
Deposit 1
Principal Amount =10000
Return Value = 16430.3
Deposit 2
Principal Amount =10000
Return Value = 16430.3
Deposit 1
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
39
Principal Amount =10000
Return Value = 14049.3
Copy Constructor
Copy Constructor is a type of constructor which is used to create a copy of an already existing object of a
class type. It is usually of the form X (X&), where X is the class name. The compiler provides a default
Copy Constructor to all the classes.
Syntax of Copy Constructor
class-name (class-name &)
{
. . . .
}
As it is used to create an object, hence it is called a constructor. And, it creates a new object, which is
exact copy of the existing copy, hence it is called copy constructor.
Copy Constructor:
One Object Member Variable Values assigned to Another Object Member Variables is called copy
constructor.
Syntax
class class-name
{
Access Specifier:
Member-Variables
Member-Functions
public:
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
40
class-name(variable)
{
// Constructor code
}
... other Variables & Functions
}
Syntax :
Argument In Main Function
ClassName Object1(value);
ClassName Object2=Object1;
Example Program
#include<iostream>
#include<conio.h>
class Example
{
// Variable Declaration
int a,b;
public:
//Constructor with Argument
Example(int x,int y)
{
// Assign Values In Constructor
a=x;
b=y;
cout<<"nIm Constructor";
}
void Display()
{
cout<<"nValues :"<<a<<"t"<<b;
}
};
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
41
int main() {
Example Object(10,20);
//Copy Constructor
Example Object2=Object;
// Constructor invoked.
Object.Display();
Object2.Display();
// Wait For Output Screen
getch();
return 0;
}
Sample Output
In Constructor
Values :10 20
Values :10 20
Dynamic Constructor:
The constructor 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 object
are not of the same size, thus resulting in the saving of memory
Allocation of memory to objects at the time of their construction is known as dynamic
construction of objects
This memory is allocated with the help of new operator
Example :
#include <iostream.h>
#include <conio.h>
class Account
{
private:
int account_no;
int balance;
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
42
public :
Account(int a,int b)
{
account_no=a;
balance=b;
}
void display()
{
cout<< "nAccount number is : "<< account_no;
cout<< "nBalance is : " << balance;
}
};
void main()
{
clrscr();
int an,bal;
cout<< "Enter account no : ";
cin >> an;
cout<< "nEnter balance : ";
cin >> bal;
Account *acc=new Account(an,bal); //dynamic constructor
acc->display(); //'->' operator is used to access the method
getch();
}
Output :
Enter accountno : 121
Enter balance : 1000
Account number is : 121
Balance is :1000
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
43
Constructing Two-dimensional Arrays:
#include<iostream.h>
#include<conio.h>
class matrix
{
int **p;
int d1,d2;
public:
matrix(int x,int y);
void getelement(int i,int j,int value)
{
p[i][j]=value;
}
int &putelement(int i,int j)
{
return p[i][j];
}
};
matrix :: matrix(int x,int y)
{
d1=x;
d2=y;
p=new int *[d1];
for(int i=0;i<d1;i++)
p[i]=new int[d2];
}
void main()
{
clrscr(); int m,n;
cout<<"Enter the size of the matrix";
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
44
cin>>m>>n;
matrix A(m,n);
cout<<"n enter matrix elements row by row n";
int i,j,value;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
cin>>value;
A.getelement(i,j,value);
}
cout<<"n";
cout<<A.putelement(1,2);
getch();
}
Output :
Enter size of matrix 3,4
Enter matrix elements row by row
11 12 13 14
15 16 17 18
19 20 21 22
17
Const Keyword
Constant is something that doesn't change. In C and C++ we use the keyword const to make program
elements constant. Const keyword can be used in many context in a C++ program. Const keyword can be
used with:
• Variables
• Pointers
• Function arguments and return types
• Class Data members
• Class Member functions
• Objects
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
45
Const class Object
When an object is declared or created with const, its data members can never be changed, during object's
lifetime.
Syntax :
const class_name object;
Const class Member function
A const member function never modifies data members in an object.
Syntax :
return_type function_name() const;
Example for const Object and const Member function
class X
{
int i;
public:
X(int x) // Constructor
{ i=x; }
int f() const // Constant function
{ i++; }
int g()
{ i++; }
};
Void main()
{
X obj1(10); // Non const Object
const X obj2(20); // Const Object
obj1.f(); // No error
obj2.f(); // No error
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
46
cout << obj1.i << obj2.i ;
obj1.g(); // No error
obj2.g(); // Compile time error
getch()
}
Output : 10 20
Here, we can see, that const member function never changes data members of class, and it can be used
with both const and non-const object. But a const object can't be used with a member function which tries
to change its data members.
Destructor :
As we know that Constructor is that which is used for Assigning Some Values to data Members
and For Assigning Some Values this May also used Some Memory so that to free up the Memory
which is Allocated by Constructor, destructor is used which gets Automatically Called at the End
of Program and we doesn’t have to Explicitly Call a Destructor and Destructor Cant be
Parameterized or a Copy This can be only one Means Default Destructor which Have no
Arguments.
For Declaring a Destructor we have to use ~tiled Symbol in front of Destructor.
Destructor is a special class function which destroys the object as soon as the scope of object ends.
The destructor is called automatically by the compiler when the object goes out of scope.
The syntax for destructor is same as that for the constructor, the class name is used for the name of
destructor, with a tilde ~ sign as prefix to it.
Syntax
class A
{
public:
~A();
};
Destructors will never have any arguments.
Example Program :
#include<iostream.h>
#include<conio.h>
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
47
int count=0;
class alpha
{
public:
alpha()
{
count++
cout<<"n No of objects created"<<count;
}
~alpha()
{
cout<<"n No of objects destroyed"<<count;
}
}
void main()
{
cout<<"n Enter main n";
alpha A1,A2,A3,A4;
{
cout<<n n "Enter Block1 n";
alpha A5;
}
{
cout<<n n "Enter Block2 n";
alpha A6;
}
cout<<n n "RE Enter MAINn";
getch();
}
OUTPUT:
No.of object created 1
No.of object created 2
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
48
No.of object created 3
No.of object created 4
Enter Block 1
No.of object created 5
No.of object destroyed 5
Enter Block 2
No.of object created 5
No.of object destroyed 5
RE Enter MAIN
No.of object destroyed 4
No.of object destroyed 3
No.of object destroyed 2
No.of object destroyed 1
Important points in unit II
C++ provides special member function called the constructor, which enables on object to initialize
itself when it is created. this is known as automatic initialization of objects.
A constructor has the same name as that of a class.
Constructors are normally used to initialize variables and to allocate memory.
Similar to normal functions, constructors may be overloaded.
When an object is created and initialized at the same time, a copy constructor gets called.
We may make an object const if it does not modify any of it's data values.
C++ also provides another member function called the destructor that destroys the objects when
they are no longer required.
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
49
UNIT-III
OPERATOR OVERLOADING
DEFINING OPERATOR OVERLOADING:
Providing additional meaning to normal operator when they are applied to user defined data types. Compiler
decides it as an over loaded operator not by looking as the data type.
We use overloaded operator for user defined data type and normal operator for built-in data type.
SYNTAX:
Return data type operator symbol of operator (parameter)
{
//body of the function;
}
TYPES OF OPERATOR OVERLOADING:
1. Unary operator overloading.
Takes one operand and no argument.
2. Binary operator overloading.
Takes two operands and one argument.
OPERATOR OVERLOADING CAN BE DONE WITH:
1. Overloading unary operator using normal member function:
It takes one operand and no argument.
2. Overloading unary operator using friend function:
It takes one operand and one argument.
3. Overloading binary operator using normal member function:
It takes two operand and one argument.
4. Overloading binary operator using friend function:
It takes two operand and two argument.
OPERATORS THAT CAN’T OVERLOADED:
1. Scope resolution operator (::)
2. Pointer variable (*)
3. Dot operator (.)
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
50
4. Conditional operator (?;)
OVERLOADING UNARY OPERATORS:
Unary operators take one operand and no argument.
PROGRAM:
#include<iostream.h>
#include<conio.h>
Class space
{
int x;
int y;
int z;
public:
void getdata (int a, int b, int c);
void display();
void operator();
};
Void space::getdata (int a, int b, int c)
{
x=a;
y=b;
z=c;
}
void space::display()
{
cout<<x<<”t”;
cout<<y<<”t”;
cout<<z<<”t”;
}
Void space::operator-()
{
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
51
x=-x;
y=-y;
z=-z;
}
Void main()
{
space s;
s.getdata(10,-20,30);
cout<<”s:”;
s.display();
-s;
cout<<”s:”;
s.display();
getch();
}
OUTPUT:
S = 10 -20 30
S = -10 20 -30
OVERLOADING BINARY OPERATORS:
It takes two operands and one argument.
PROBLEM ARISES:
How 2 operands can be passed in a single argument.
Example:
t3 = t1+t2; t2 alone passed to operator function.
PROGRAM:
#include<iostream.h>
#include<conio.h>
Class binadd
{
int a,b;
public:
void getvalue()
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
52
{
cout<<”Enter the a,b values”;
cin>>a>>b;
}
binadd operator+(binadd ob)
{
binadd t;
t.a =a + ob.a;
t.b =b + ob.b;
return(t);
}
binadd operator-(binadd ob)
{
binadd t;
t.a =a-ob.a;
t.b=b-ob.b;
return(t);
}
void display()
{
cout<<a<<b<<”n”;
}
};
void main()
{
clrscr();
binadd obj1,obj2,result,result1;
obj1.getvalue();
obj2.getvalue();
result=obj1+obj2;
result1=obj1-obj2;
cout<<”Input values”;
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
53
obj1.display();
obj2.display();
cout<<”Result”;
result.display();
result1.display();
getch();
}
OUTPUT:
Enter the a,b values 1 2
Enter the a,b values 1 2
Input values
1 2
1 2
Result
2 4
0 0
OVERLOADING BINARY OPERATORS USING FRIEND FUNCTION:
It takes two operand and two arguments.
PROGRAM:
#include<iostream.h>
#include<conio.h>
Class binary
{
int a,b;
public:
void get()
{
cout<<”Give values”;
cin>>a>>b;
}
void display()
{
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
54
cout<<a<<b<<”n”;
}
friend binary operator-(binary u, binary v);
};
Binary operator-(binary u, binary v)
{
binary s;
s.a=u.a-v.a;
s.b=u.b-v.b;
return(subha);
}
void main()
{
clrscr();
binary obj1,obj2,result;
obj1.get();
obj2.get();
result=obj1-obj2;
cout<<”Input values”;
obj1.display();
obj2.display();
cout<<”Result”;
result.display();
getch();
}
OUTPUT:
Give values 10 20
Give values 5 10
Input values
10 20
5 10
Result
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
55
5 10
RULES FOR OPERATOR OVERLOADING:
1. Only existing operators can be overloaded. New operator cannot be overloaded.
2. The overloaded operator must have atleast one operand that is of user defined data type.
3. We cannot change the basic meaning of an operator. That is to say, we cannot redefine the plus(+) operator to
subtract one value from the other.
4. Overloaded operators follow the syntax rules of the original operators. They cannot be overridden.
5. There are some operators that cannot be overloaded like size of operator (size of), membership operator(.),
pointer of member operator(*), scope resolution operator(::), conditional operator(?:).
6. We cannot use “friend” function to overload certain operators. However member function can be used to
overload them. Friend functions cannot be used with assignment operator(=), function call operator(()),
subscripting operator([]), class member access operator(->).
7. Unary operators overloaded by means of a member function take no explicit arguments and return no explicit
values, but those overloaded by means of a friend function, take one reference argument. (the object of the
relevant class)
8. Binary operator overloaded through a member function take one explicit argument and those which are
overloaded through a friend function take two explicit arguments.
9. When using binary operators overloaded through a member function, the left hand operand must be an object
of the relevant class.
10. Binary arithmetic operators such as +,-,*,/ must explicitly returns a value. They must not attempt to change
their own argument.
Program to perform string manipulation using operators
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class string
{
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
56
protected:
char str[25];
public:
void getstring();
void display();
string operator+(string&);
int operator==(string&);
void operator=(string&);
void operator+=(string&);
};
void string::getstring()
{
cout<<"Enter string:";
gets(str);
}
string string::operator+(string &s)
{
string temp;
if((strlen(str)+strlen(s.str))<25)
{
strcpy(temp.str,str);
strcat(temp.str,s.str);
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
57
}
else
{
cout<<endl<<"concatenation is not possible";
}
return temp;
}
int string::operator==(string &s)
{
return(strcmp(str,s.str)==0?1:0);
}
void string::operator=(string &s)
{
strcpy(str,s.str);
}
void string::operator+=(string &s)
{
strcat(str,s.str);
}
void string::display()
{
cout<<str;
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
58
}
void main()
{
string s1,s2,s3,s4;
clrscr();
s1.getstring();
s2.getstring();
s3=s1+s2;
cout<<endl<<"Concatenated string:";
s3.display();
if(s1==s2)
cout<<endl<<"Comparison:Equal";
else
cout<<endl<<"Comparison:Not equal";
cout<<endl<<"after addition:";
s1+=s2;
s1.display();
s4=s3;
cout<<endl<<"copy:";
s4.display();
s1=s2;
getch();
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
59
}
Output:
Enter string:Mohamed
Enter string:Riyazudeen
Concatenated string:MohamedRiyazudeen
Comparison:Not equal
After addition: MohamedRiyazudeen
Copy: MohamedRiyazudeen
Type Conversions:
C++ has wide variety of data types ranging from the basic or primitive data types to the user defined data
types.
It is easier to convert same type of data from one to the other. For instance if we have two integer
variables say
Code:
int num1, num2;
The compiler will automatically convert them from one form to other if an equal’s sign is used between these
two. For example
Code:
num1 = num2;
will be automatically compiled by the compiler and no explicit logic needs to be embedded in the code. This is
the case with basic data types.
Now, come towards the user defined data types or what we call objects. In our article on operator overloading we
explained how we can assign two variables of one user defined data types to each other. For example if we had
class class1, we could create two objects of class1 like
Code:
class1 obj1, ob2;
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
60
obj1=obj2
In that all the values from the variables of obj2 will be copied into the corresponding variables of obj1.
In both of our examples we are storing values between variables of same data type. First we stored data from an
integer to another integer and then we stored user defined objects of class1 to another object of class1.
What if we want to store a float type data into an integer or an object of class1 into another object of class2 i.e.
the data type of both of these objects will be different.
Three types of situations might arise in the data conversion between uncompatible types
1. Conversion from basic type to class type
2. Conversion from class type to basic type.
3. Conversion from one class type to another class type.
Conversion from basic to class type:
Now let us consider another example for converting an int to a class type.
class distance
{
private:
int kilometers;
int meters;
public:
distance(int meters) // constructor
{
kilometers = meters / 1000;
meters = meters % 1000;
}
}
The following conversion statements can be used in a function such as main:
distance D1; // object D1 created
int distance_covered = 10050;
D1 = distance_covered; // int to class type
After the execution of the 3rd statement, kilometers will hold the value 10 and meters will have the value 50.
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
61
Thus, we see that the constructors used for the type conversion take a single argument whose type is to be
converted
Sample Program
/*
* Program that converts from miles to kilometers.
* Illustrates type conversion from built-in types
* to user-defined types.
*/
#include<iostream>
using namespace std;
class DistConv
{
private:
int kilometers;
double meters;
const static double kilometersPerMile;
public:
// This function converts a built-in type (i.e. miles) to the user-defined type (i.e. Distconv)
DistConv(double mile) // Constructor with one argument
{
double km = kilometersPerMile * mile ; // converts mile to Km
kilometers = int(km); // converts float Km to int and assigns to kilometer
meters = (km - kilometers) * 1000 ; // converts to meter
}
void display(void)
{
cout << kilometers << " kilometers and " << meters << " meters n" ;
}
}; // End of the Class Definition
const double DistConv::kilometersPerMile = 1.609344;
int main(void)
{
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
62
DistConv d1 = 5.0 ; // Uses the constructor with one argument
cout << "5.0 miles = " ;
d1.display( ) ;
d1 = 2.0 ; // This form also uses the constructor with one argument
cout << "2.0 miles = " ;
d1.display( ) ;
}
Output
5.0 miles = 8 Kilometers and 46.72 meters
2.0 miles = 3 Kilometers and 218.688 meters
Type Conversion – Class to Basic Type
The constructor handles the task of converting basic types to class types very well.
But you cannot use constructors for converting class types to basic data types.
Instead, you can define an overloaded casting operator that can be used to convert a class data type into a
basic data type.
The general form of an overloaded casting operator function is shown below.
This function is also known as a conversion function.
Syntax:
operator typename()
{
-----------
function body
-----------
}
The above function converts the class type into the typename mentioned in the function. For example, operator
float( )converts a class type to float, operator int() converts a class type to int, and so on.
The casting operator function should satisfy the following conditions:
It must be a class member.
It must not specify a return type.
It must not have any arguments. The object that invokes this function has its members directly accessible
since this is a member function.
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
63
Sample Program
/*
* Program that converts between kilometers and miles.
* Illustrates type conversion from a class type
* to a built-in type.
*/
#include<iostream>
class DistConv
{
private:
int kilometers;
double meters;
nbsp; const static double kilometersPerMile;
public:
// This function converts a built-in type (i.e. miles) to the
// user-defined type (i.e. DistConv)
DistConv(double mile) // Constructor with one
// argument
{
double km = kilometersPerMile * mile ; // converts miles to
//kilometers
kilometers = int(km); // converts float km to
//int and assigns to kilometer
meters = (km - kilometers) * 1000 ; // converts to meters
}
DistConv(int k, float m) // constructor with two
// arguments
{
kilometers = k ;
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
64
meters = m ;
}
// ********Conversion Function************
operator double() // converts user-defined type i.e.
// DistConv to a basic-type
{ // (double) i.e. meters
double K = meters/1000 ; // Converts the meters to
&nsp; // kilometers
K += double(kilometers) ; // Adds the kilometers
return K / kilometersPerMile ; // Converts to miles
}
void display(void)
{
cout << kilometers << " kilometers and " << meters << " meters" ;
}
}; // End of the Class Definition
const double DistConv::kilometersPerMile = 1.609344;
int main(void)
{
DistConv d1 = 5.0 ; // Uses the constructor with one argument
DistConv d2( 2, 25.5 ); // Uses the constructor with two arguments
double ml = double(d2) ; // This form uses the conversion function
// and converts DistConv to miles
cout << "2.255 kilometers = " << ml << " milesn" ;
ml = d1 ; // This form also uses conversion function
// and converts DistConv to miles
d1.display();
cout << " = " << ml << " milesn" ;
}
Output
2.255 kilometers = 1.25859 miles
8 kilometers and 46.72 meters = 5 miles
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
65
Type Conversion – Class to Class
Now that we have understood how to convert basic data types to class types and vice-versa, it is time to
learn how to convert objects of one class type to another class type.
The conversion between objects of different classes can be done using either a one-
argument constructor or a conversion function.
The choice depends upon whether the conversion routine has to be declared in the source class or in the
destination class.
To illustrate, consider a program that contains two classes: A and B. Also consider the statement:
object_A = object_B;
In the above statement, object_B of type B is converted to typeA and assigned to object_A.
Therefore, object_B is the source and object_A is the destination.
For the conversion, the user can use either a conversion function or a constructor with one argument,
depending on whether it is specified in the source class or the destination class.
In other words, if class B handles the conversion, it will hold a conversion function. On the other hand, if
class A carries out the conversion, it will do that through a constructor that takes an argument of type class
B.
Note that only one of the two conversion routines should be specified; the compiler will yield an error if
both are specified since it will not be able to figure out which routine to call.
Sample Program
/*
* Program converts from one class type to
* another using a conversion function
* and a constructor
*/
#include <iostream>
using namespace std;
class Kilometers
{
private:
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
66
double kilometers;
public:
Kilometers(double kilometers): kilometers(kilometers) {}
void display()
{
cout << kilometers << " kilometeres";
}
double getValue()
{
return kilometers;
}
};
class Miles
{
private:
double miles;
public:
Miles(double miles) : miles(miles) {}
void display()
{
cout << miles << " miles";
}
operator Kilometers()
{
return Kilometers(miles*1.609344);
}
Miles(Kilometers kilometers)
{
miles = kilometers.getValue()/1.609344;
}
};
int main(void)
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
67
{
/*
* Converting using the conversion function
*/
Miles m1 = 100;
Kilometers k1 = m1;
m1.display();
cout << " = ";
k1.display();
cout << endl;
/*
* Converting using the constructor
*/
Kilometers k2 = 100;
Miles m2 = k2; // same as: Miles m2 = Miles(k2);
k2.display();
cout << " = ";
m2.display();
cout << endl;
}
Output
100 miles = 160.934 kilometeres
100 kilometeres = 62.1371 miles
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
68
Key Points:
Operator overloading is one of the important feartures of C++ language. It is called compile time
polymorphism.
Using overloading feature we can add two user defined data types such as objects, with the same syntax,
just as basic data types.
We can overload almost all the C++ operators except the following:
Class member access operators(.,.*)
Scope resoulation operator(::)
Size operator(sizeof)
Conditional Operator(?:)
The compiler does not support automatic type conversions for the user defiend data types. We use casting
operator function to achieve this
The casting operator function should satisfy the following conditions
It must be a class member
It must not specify a return type
It must not have any arguments
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
69
UNIT IV
INHERITANCE:
Inheritance is the process of creating new classes, called derived classes from an existing class,
called base class.
The derived class inherits all capabilities of the base class. It can also add some more features of
this class. The base class is unchanged by its process.
ADVANTAGES:
1. It permits reusability of the code.
2. Increases the reliability of the code.
3. It adds some enhancements to the base class.
Inheritance is classified into the following forms:
1. Single Inheritance.
2. Multiple Inheritance.
3. Hierarchical Inheritance.
4. Multilevel Inheritance.
5. Hybrid Inheritance.
DEFINING DERIVED CLASSES:
A derived class is defined by specifying its relationship with the base class in addition to its own features.
No memory is allocated to the declaration of a derived class, but memory is allocated when it is instantiated to
create objects.
SYNTAX:
Class derived class:[visibility mode] base class
{
// Members of derived class and can access
// Members of the base class
};
Where derived class is the derived class name. Visibility mode is the inheritance type. It may be public or
private. The default is private. Base class is the base class name. The Colon(:) indicates the derivation of
derived class from the base class.
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
70
The three possible styles of derivations are given below
1. Class A : Public D //public derivation
{
//members of A
};
2. Class A : private D
{
//members of A
};
3. Class A:D
{
//members of D
};
When a base class is publicly inherited, public members of the base class become public members of the derived
class and the protected members of the base class become protected members of the derived class.
The table given below shows the visibility of class members
Base class visibility Derived class visibility
Public derivation Private derivation
Private Not Inherited Not Inherited
Protected Protected Private
Public Public Private
MAKING A PRIVATE MEMBER INHERITABLE:
It is observed that a private member of a base class cannot be inherited and therefore it is not
available for the derived class directly.
To inherit the private data and functions, we have to convert the visibility modifier as either public
or protected.A member declared as protected is accessible by the member functions within its class
any class immediately derived from it. It cannot be accessed by the functions outside these two
classes.
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
71
A class can now use all the three visibility modes as illustrate here.
Class sample
{
Private: //optional
…………. //visible to member function within its class
Protected:
………….. //visible to member functions of its own and derived class
Public:
…………… //visible to all functions in the program
};
The various categories of functions which have access to the private and protected member could be
1. A member function of a class.
2. A member function of a derived class
3. A friend function of a class
4. A member function of a friend class
The following table summarize the scope of access in various situations:
Function Type Access directly to
Private Protected Public
Class Member Yes Yes Yes
Derived Class
Member
No Yes Yes
Friend Yes Yes Yes
Friend class member Yes Yes Yes
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
72
Single Inheritance
In this type of inheritance one derived class inherits from only one base class. It is the most simplest form of
Inheritance.
 Single Inheritance
#include<iostream.h>
#include<conio.h>
class first //base or parent class
{
public: //Access Specifier
int a,b;
void getdata() //member function getdata()
{
cout<<"nEnter Number :::t";
cin>>a>>b;
}
void putdata() //member function putdata()
{
cout<<"nNumber Is :::t"<<a<<"t"<<b;
}
};
class second :public first //class second inherits property of class first
{
public : //Access Specifier
int c;
void add()
{
getdata();
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
73
putdata();
c=a+b;
cout<<"nnAnswer :::t"<<c;
}
};
int main()
{
clrscr();
second s1; //s1 is object of class second
s1.add();
getch();
}
Output:
Enter Number ::: 10 50
Number is ::: 10 50
Answer ::: 60
Multiple Inheritance
In this type of inheritance a single derived class may inherit from two or more than two base classes.
Multiple Inheritance in c++
#include<iostream.h>
#include<conio.h>
class A // Base class 1
{
public:
int a;
void First()
{
cout<<"nnFirst Number :::t";
cin>>a;
}
};
class B //Base class 2
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
74
{
public:
int b;
void second()
{
cout<<"nnSecond Number :::t";
cin>>b;
}
};
//Multiple Inheritance Level
class C :public A,public B // Class C is derived class
{
public:
int c;
void result()
{
First();
second();
c=a+b;
cout<<"nnResult :::t"<<c;
}
};
int main()
{
clrscr();
C c1;
c1.result();
getch();
}
Output:
First Number ::: 40
Number is ::: 20
Answer ::: 60
Hierarchical Inheritance
In this type of inheritance, multiple derived classes inherits from a single base class.
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
75
Hierarchical inheritance in c++
#include<iostream.h>
#include<conio.h>
class A //Base Class
{
public:
int a,b;
void getnumber()
{
cout<<"nnEnter Number :::t";
cin>>a;
}
};
class B : public A //Derived Class 1
{
public:
void square()
{
getnumber(); //Call Base class property
cout<<"nntSquare of the number :::t"<<(a*a);
cout<<"nnt----------------------------------------------------";
}
};
class C :public A //Derived Class 2
{
public:
void cube()
{
getnumber(); //Call Base class property
cout<<"nntCube of the number :::t"<<(a*a*a);
cout<<"nnt----------------------------------------------------";
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
76
};
int main()
{
clrscr();
B b1; //b1 is object of Derived class 1
b1.square(); //call member function of class B
C c1; //c1 is object of Derived class 2
c1.cube(); //call member function of class C
getch();
}
Output:
Enter the Number 2
Square Number :::4
……………………………………………………
Enter the Number 3
Cube Number ::: 27
Multilevel Inheritance
In this type of inheritance the derived class inherits from a class, which in turn inherits from some other class.
The Super class for one, is sub class for the other.
Multilevel Inheritance in c++
#include<iostream.h>
#include<conio.h>
class top //base class
{
public :
int a;
void getdata()
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
77
{
cout<<"nnEnter first Number :::t";
cin>>a;
}
void putdata()
{
cout<<"nFirst Number Is :::t"<<a;
}
};
//First level inheritance
class middle :public top // class middle is derived_1
{
public:
int b;
void square()
{
getdata();
b=a*a;
cout<<"nnSquare Is :::"<<b;
}
};
//Second level inheritance
class bottom :public middle // class bottom is derived_2
{
public:
int c;
void cube()
{
square();
c=b*a;
cout<<"nnCube :::t"<<c;
}
};
int main()
{
clrscr();
bottom b1;
b1.cube();
getch();
}
OUTPUT
ENTER THE NUMBER ::: 4
SQUARE IS::: 16
CUBE IS ::: 64
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
78
Hybrid (Virtual) Inheritance
Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance.
Hybrid inheritance is combination of two or more inheritances such as single, multiple, multilevel or
Hierarchical inheritances.
In the above program class B inherits property(member function) of class A which is base class and class
D inherits property from class B and class C.
#include<iostream.h>
#include<conio.h>
class A //Base class
{
public:
int l;
void len()
{
cout<<"nnLenght :::t";
cin>>l; //Lenght is enter by user
}
};
class B :public A //Inherits property of class A
{
public:
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
79
int b,c;
void l_into_b()
{
len();
cout<<"nnBreadth :::t";
cin>>b; //Breadth is enter by user
c=b*l; //c stores value of lenght * Breadth i.e. (l*b) .
}
};
class C
{
public:
int h;
void height()
{
cout<<"nnHeight :::t";
cin>>h; //Height is enter by user
}
};
//Hybrid Inheritance Level
class D:public B,public C
{
public:
int res;
void result()
{
l_into_b();
height();
res=h*c; //res stores value of c*h where c=l*b and h is height which is enter by user
cout<<"nnResult (l*b*h) :::t"<<res;
}
};
int main()
{
clrscr();
D d1;
d1.result();
getch();
}
irtual Base Class:
Why we need virtual base Class:
we have already discussed on “Inheritance” that multiple inheritance is a process of creating a new classes
which is derived from more than one base classes.
Output:
Length : : : 20
Breath : : : 30
Height : : : 40
Result (l*b*h) : ; : 24000
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
80
Multiple inheritance hierarchies can be complex, which may lead to a situation in which a derived class
inherits multiple times from the same indirect base class.
For example the program segment given below illustrates how a base class can be derived twice from the
derived class in different way.
class A
{
protected:
int x;
...........
};
class B : public A
{
protected:
...........
...........
};
class D :public A
{
protected:
................
................
};
class abc : public B, public D
{
// the data member X comes twice
......................
......................
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
81
};
The data member X is inherited in the derived class abc, one through the derived class B and again
through D. this is waste and confusing.
The above multiple repetition of the data can be corrected by changing the derived class B and D into
virtual base classes.
Virtual Base Classes:
Any base class which is declared using the keyword virtual is called a virtual base class. It is important to
avoid unnecessary reputation of the same data member in the multiple inheritance hierarchies
class A
{
protected:
int x;
...........
};
class B : virtual A
{
protected:
...........
...........
};
class D :virtual A
{
protected:
................
................
};
class abc : public B, public D
{
// the data member X comes only once
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
82
......................
......................
};
By making B and D into virtual base classes for abc, a copy of the datamember X is available only
once.
A class may be both an ordinary and virtual base in the same inheritance structure
#include<iostream.h>
#include<conio.h>
class student
{
int rno;
public:
void getnumber()
{
cout<<"Enter Roll No:";
cin>>rno;
}
void putnumber()
{
cout<<"nntRoll No:"<<rno<<"n";
}
};
class test:virtual public student
{
public:
int part1,part2;
void getmarks()
{
cout<<"Enter Marksn";
cout<<"Part1:";
cin>>part1;
cout<<"Part2:";
cin>>part2;
}
void putmarks()
{
cout<<"tMarks Obtainedn";
cout<<"ntPart1:"<<part1;
cout<<"ntPart2:"<<part2;
}
};
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
83
class sports:public virtual student
{
public:
int score;
void getscore()
{
cout<<"Enter Sports Score:";
cin>>score;
}
void putscore()
{
cout<<"ntSports Score is:"<<score;
}
};
class result:public test,public sports
{
int total;
public:
void display()
{
total=part1+part2+score;
putnumber();
putmarks();
putscore();
cout<<"ntTotal Score:"<<total;
}
};
void main()
{
result obj;
clrscr();
obj.getnumber();
obj.getmarks();
obj.getscore();
obj.display();
getch();
}
Output:
Enter Roll No: 200
Enter Marks
Part1: 90
Part2: 80
Enter Sports Score: 80
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
84
Roll No: 200
Marks Obtained
Part1: 90
Part2: 80
Sports Score is: 80
Total Score is: 250
Abstract Class
Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes are used to
provide an Interface for its sub classes. Classes inheriting an Abstract Class must provide definition to the pure
virtual function, otherwise they will also become abstract class.
Characteristics of Abstract Class
Abstract class cannot be instantiated, but pointers and refrences of Abstract class type can be created.
Abstract class can have normal functions and variables along with a pure virtual function.
Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface.
Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will become
Abstract too.
CONSTRUCTORS IN DERIVED CLASSES:
The constructor play an important role in initializing an object’s data members and allocating required
memory.
The derived class need not have a constructor as long as the base has a no argument then it is mandatory
for the derived class to have a constructor and pass the arguments to the base class constructor.
The syntax for defining a constructor in a derived class is shown below.
Derived class(arglist):Base 1(arglist)…………Base N(arglist M)
{
//body of the constructor of derived class
};
EXAMPLE
D (int a1, a2, float b1, float b2, int d1);
A(a1, a2), /*call to constructor A*/
B (b1,b2), /*call to constructor B*/
{
d=d1; //executes its own body
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
85
A(a1,a2) invokes the base constructor A() and B(b1,b2) invokes another base constructor B(). The constructor
D() supplies the values for these four arguments. In addition it has one argument of its own. The constructor D()
has a total of five arguments. D() may be invoked as follows.
……………………….
D obj D (15, 72, 2.5, 17.54, 30);
……………………….
These values are assigned to various parameters by the constructor D() as follows.
15 a1
72 a2
2.5 b1
17.54 b1
30 d1
The following table shows the order of invocation of constructors in a derived class.
Method of inheritance Order of execution
Class D:public B
{
………………………
};
B() : base constructor
D() : derived constructor
Class D:public B1,public B2
{
………………….
};
B1() : base constructor
B2() : base constructor
D() : derived constructor
Class D1:public B1, virtual B2
{
……………………
};
B2() : virtual base constructor
B1() : base consructor
D() derived constructor
Class D1:public B
{
…………………………
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
86
};
Class D2:public D1
{
…………………………
};
B():super base constructor
D1() : base constructor
D2(): derived constructor
MEMBER CLASSES – NESTING OF CLASSES
When a class is declared and defined as a member of another class, it is known as a nested class.
C++ allows to have an object of a class as a member of another class.
When an object of a class is declared as a member of another class, it is called as container class.
EXAMPLE
Class C
{
………….
A a;
B b;
Public:
C (arglist): a(arglist 1), b( arglist 2)
{
//constructor body
}
};
Arglist is the list of arguments that is to be supplied when C object is defined. These are used to initialize
the members of C.
Arglist1 & arglist2 may or may not use the arguments from arglist, a&b are function calls and therefore
the argument do not contain the data types
Key Points :
The mechanism of deriving a new class from an old class is called inheritance. Inheritance provides the
concept of reusability. The C++ classes can be reused using inheritance.
A private member of class cannot be inherited either in public mode or private mode.
A protected member inherited in public mode becomes protected, whereas inherited in private mode
becomes private in the derived class.
A public member inherited in public mode becomes public, whereas inherited in private mode becomes
private in the derived class.
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
87
The friend function and the member functions of a friend class can directly access the private and
protected data.
A class can contain object of other class. This is known as containership or nesting
UNIT V
INTRODUCTION
A file is a collection of related information. A file is referred by its name. A file contains a
collecting of related data stored in a particular area on the disk.
The operating system provides most of the essential file manipulation services such as create,
open, write, read, rewind, close and delete.
A program invokes either or both of the following data communications.
1. Data transfer between the console unit and the program.
2. Data transfer between the program and a disk file.
In C++ I/O system takes care of file operations. The file streams are moving between the disk and the
program. The movement of data between the disk files and IO stream in a program is shown in below:
Read Data
Data Input
Write Data Data Output
The input stream supplies data to the program and the output stream receives data from the program.
CLASSES FOR FILE STREAM OPERATIONS
In C++ the I/O stream contains a set of classes to define the file handling methods. There are three classes
for handling files. They are
1. ifstream - handling input files
2. ostream - handling output files
3. fstream - for both input&output files
Input Stream
Output Stream
Disk
Files
Programs
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
88
The actions performed by classes related to file management are given below:
filebuf:
Sets the file buffer to read and write.
It contains openprot constant used in open() of file stream class and also contains close() as
member.
fstreambase:
Supports operations common to the file streams.
It is the base class for ifstream, ofstream and fstream classes.
It contains open() and close() member functions.
ifstream:
Support input operations.
It contains open() with default mode and inherits get(), getline(), read(), seekg() and tellg()
functions from istream.
ofstream:
Supports output operations.
It contains open() with default output mode and inherits put(), seekp(), tellp() and writer()
functions from ostream.
fstream:
Supports I/O operations.
It contains open() with default input mode and inherits all the functions from istream and ostream
through iostream.
OPENING AND CLOSING OF FILES
In C++, a file can be opened in two ways
1. using constructors
2. using the function open() of the class
After processing an operand file, it must be closed.
It can be closed either by explicitly using the close() member function of the class or it is
automatically closed by the destructor of the class, when the file stream object goes out of scope.
1. OPENING FILES USING CONSTRUCTORS
Constructor is a member function. It initializes the objects.
SYNTAX:
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
89
Class objectname(value);
Where class may be ofstream or ifstream
objectname is the valid C++ variable
variable is the string of characters within””.
OPENING A OUTPUT FILE
SYNTAX:
Ofstream fileobject(“filename”);
OPENING A INPUT FILE
SYNTAX:
Ifstream fileobject(“filename”);
where ifstream is the class name
fileobject is the input file object name
filename is the input file to be created
Example: ifstream employee(“emp.dat”);
CLOSING A FILE
All the opened files must be closed before the end of the program.
SYNTAX
fileobject.close();
Example: employee.close();
WRITING AND READING FILES
To write data into the opened output file, the following syntax may be used.
Fileobject<<data1<<data2<<………<<dataN;
To read from the opened input file, the following syntax may be used.
Fileobject>>data1>>data2>>……..dataN;
Where
Fileobject – is the file object name of the opened output/input file
>>(or)<< - overloaded operator
Data1, data2,…..dataN – data to write into the file or data to read from the file.
PROGRAM
Program to create a file student.out using constructor and writes student details into it.
/*Student file, creating file with constructor*/
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
90
#include<fstream.h>
void main()
{
char name[30];
int marks;
ofstream fout(“student.out”)
cout<<”Enter Name:”; //read first students details
cin>>name;
cout<<”Enter marks secure:”;
cin>>marks;
fout<<name<<endl; //write to a file
fout<<marks<<endl;
cout<<”Enter Name:”; //read second student details
cin>>name;
cout<<”Enter marks secure:”;
cin>>marks;
fout<<name<<endl; //write to a file
fout<<marks<<endl;
}
Output:
Enter Name : Ajjai
Enter Marks Secured : 95
Enter Name : Aravind
Enter marks Secured : 90
Ajjai
95
Aravind
90
2.OPENING FILES USING OPEN()
The function open() can be used to open multiple files that use the same stream object.
To open an output file, the syntax is
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
91
Ofstream fileobject:
Fileobject.open(“filename”);
Example:
ofstream employee:
employee.open(“emp.dat”);
To open an input file, the syntax is:
Ifstream fileobject;
Fileobject.open(“filename”);
DETECTING END OF FILES
Detection of the end-of-file condition is necessary to prevent any further attempt to read data from file.
This can be done in two ways.
They are
1. using the member function “eof”
2. using objects
USING MEMBER FUNCTION
eof() is a member function of ios. It is used to detect the end of file condition. It returns non-zero value at
the end of file condition is encountered and a zero otherwise.
SYNTAX:
Objectname.eof()!=0
Where object is the objectname used in the open command.
USING OBJECTS
Another indirect way for detecting the end-of-file conditions is that the file object itself has to be tested. It
returns value of zero, if any error occurs in the file operation, including the end-of-file condition. If the eof
condition is reached, it is considered as an error. Hence value 0 is returned. Thus the file object can be used to
check the condition.
SYNTAX:
While(objectname)
{
………………….
…………………
}
where objectname is the object name used in the open command.
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
92
FILE MODES
C++ provides a facility to open a file in different modes, in which case the argument must be explicitly
passed. The table shows the list of file modes with mode value and their meaning
Mode value Effect on the mode
ios::in Open for reading
ios::out Open for writing
ios::ate File pointer goes to the end of file
ios::app Open the file in append mode
ios::trunk Truncate the file if it is already exist
ios::nocreate Open fails if the file does not exist
ios::noreplace Open fails if the file exists already
ios::binary Open as a binary file
The mode of the file must be specified at the time of opening.
Its syntax are:
(i)using constructor
fstream fileobjectname(arg1, arg2);
where
fstream -classname
fileobjectname-name of the object
arg1 - name of the file to create in the disk. This should be within double
quotes
arg2 - flag/mode value
Example
fstream employee(“emp.dat”,ios::in);
This opens the file in input mode.
(ii)using member function
Fstream fileobjectname;
Fileobjectname.open(arg1, arg2)
where
fstream - class name
fileobjectname- name of the object
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
93
arg1 - name of the file to create in the disk. This should be within double quotes.
arg2 - flag/ mode value.
Example
fstream student;
employee.open(“emp.dat”, ios::app);
This opens the file in append mode.
FILE POINTERS AND THEIR MANIPULATION
Each file object has two associated pointers known as file pointers.
Some time it may be required to position the pointer of file at any place in the file or to know the current file
position .
In C++ there are two types of pointer. They are
1. Input pointer (or) get pointer
2. Output Pointer (or) put pointer
The get pointer specifies a location from where the current reading operation is initiated. That is get
pointer indicating the position for an input file
The put pointer indicates the position for an output file. It specifies a location from wherse the current
writing operation is initiated.
Functions For Manipulation of File pointer.
In C++ I/O system supports four functions for setting a file pointer to any desired position inside the file or to
get current file pointer.
It allows to control a position in the file where read/write operation takes place.
1. Seekg()
2. Seekp()
3. Tellg()
4. Tellp()
i. seekg()
It is member of class ifstream. It moves get file pointer to a specified location. It’s syntax is
Where
File_nameobject – name of the object
Pos – byte number to move
Filename_object.seekg(pos,flag);
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
94
Flag – the position from to move This is optional
The table given below shows the possible flags available
Flag Meaning
ios::beg Sets the pointer at the beginning of the file
ios::cur Sets the pointer in the current position
ios::end Sets the pointer at the end of the file
Example :
Fstream employee
Employee.open(“employee.dat”,ios::in);
Employee.seekg(10);
When student .seekg(12) is executed, the get file pointer is moved to 12th
byte from start
ii. seekp()
It is the member of the class ofstream. It moves put file pointer to specified position. Its syntax is
Where
File_nameobject – name of the object
Pos – byte number to move
Flag – the position from to move This is optional
The table given below shows the possible flags available
Flag Meaning
ios::beg Sets the pointer at the beginning of the file
ios::cur Sets the pointer in the current position
ios::end Sets the pointer at the end of the file
Example :
Fstream employee
Filename .object.seekp(ps,flag);
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
95
Employee.open(“employee.dat”,ios::out);
Employee.seekg(10);
When student .seekg(12) is executed, the get file pointer is moved to 12th
byte from start
iii. tellg()
It is the member class of ifstream. It returns the byte number of the current position of the get file pointer. It is
syntax is
Example :
Fstream employee
Employee.open(“employee.dat”,ios::in);
Employee.seekg(12);
Int p = employee.tellg();
When the above statements are executed 12 is assigned to p
iv. tellp()
it is member class of ofstream. It returns the byte number of the current position of the output pointer.
The general form is
Where
File_nameobject - name of the object
Var 1 - valid C++ variable
Example :
Fstream employee
Employee.open(“employee.dat”,ios::out);
Employee.seekg(12);
Int p = employee.tellg();
When the above statements are executed 12 is assigned to p.
SEQUENTIAL INPUT AND OUTPUT OPERATIONS
Sequential input operations
There are two member functions are available for sequential input operation. They are
1. get()
2. read()
Int var 1 = filename_object.tellp();
Int var 1 = filename_object.tellg();
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
96
1.get()
The get() is a member function of the fstream class
This function reads the file character by character and assigns it to the given character variable. Its syntax is
File object name.get(variable);
(ii) read()
This read() function access data in binary form. It reads a block of binary data pointed by the get file
pointer and assigns it to the pointer variable. Its syntax is
file objectname.read(char*)&variable,size of (variable);
where
(char*)&variable - address of the character type variable.
Sizeof(variable) - length of the variable in bytes.
Sequential output operation
1. put()
2. write()
(i)put()
The put() function is used to write character by character into the file. Its syntax is
file objectname.put(variable);
(ii)write()
The write() function used to write a block of binary data into the file. Its syntax is
File objectname.write(char*)variable sizeof(variable);
UPDATING A FILE : RANDOM ACCESS
Updating is an usual task in the maintenance of any data file. Updating includes any one or more of the
following.
1. Displaying the file contents
2. Modification of existing data
3. Adding a new data
4. Deleting an existing items
The above actions requires movement of file pointer(get or put) from one position to another. This can be done
easily by using the seek(), read() and write() functions.
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
97
ERROR HANDLING DURING FILE OPERATIONS
During the manipulations, the reading or writing operation any be failed due to the following.
1. Attempt to open a non-existing file in read-mode.
2. Try to open a read-only file in write mode.
3. Try to open a file with invalid name.
4. Insufficient disk space while writing to a file.
5. Try to access beyond the EOF.
6. Attempt to perform an unopened file.
7. Stream object created but not connected to a file.
8. Disk error during reading or writing operations.
Such situation must be detected while accessing files and necessary action should be taken to access the
file without error.
Every stream (ifstream, ofstream and fstream) has a state associated with it. Errors and understand
conditions are handled by setting and testing this state.
The ios class supports several function to access the status recorded in the data member io-state.
The following table shows the Error handling functions and their return values.
FUNCTION MEANING OF RETURNS VALUE
eof() It is used to check the end of file. It returns 1 if EOF is encountered
while reading otherwise returns 0.
fail() It is used to inform the failures in input or output operation. It returns 1 if
read or write operation has failed otherwise returns 0.
bad() It is used to check for unrecoverable errors. It returns 1 if an invalid
operation is attempted or any unrecoverable errors, occurs returns 0.
Otherwise, however it can be recovered.
good() It is used to check whether the file is having any errors. It returns 1 if
there is no error i.e., above all the functions are false.
The following examples illustrates checking errors during the operations.
1.opening a non-existent file in read mode
Ifstream infile(“my file”):
If (linfile)
{
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
98
//file does not exist
}
2.open fail : opening read-only file
Ofstream outfile (“my file”);
If (linfile) // or if(infile.bad())
{
//file exist already and marked as read only
}
3.invalid file name
Infile open(“-*”);
{
//invalid file name
}
4.read fail
Infile.read(…);
In(infile.bad())
{
//file cannot be accessed further
}
5.processing unopened file
Infile.read(…);
If(infile.fail())
{
//file is not opened
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
99
COMMAND LINE ARGUMENTS
Command line arguments are arguments that allows parameters to be passed to main() from shell prompt.
There are two arguments available. They are
1. argc - it is an integer variable
2. argr - it is an array of pointers to characters.
For instance,
Main(int argc, char*argv[])
The first argument argc(known as argument counter)represents the number of arguments in the command line.
The second argument argv(known as argument vector) is an array of char type pointers that point to the
command line arguments. The size of the array will be equal to the value of argc.
Suppose our program is sample, if we execute the file in the command prompt as
c:>sample file1 file2 file3
then the value of argc would be 4 and the argv would be array of 4 pointer to string as
argv[0] -> sample(always represents the command name)
argv[1] -> file1
argv[2] -> file2
argv[3] -> file3
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
100
PRACTICAL PROGRAMS WITH OUTPUT
1. PROGRAM USING ARRAYS WITHIN ACLASS
#include<iostream.h>
#include<conio.h>
class student
{
int regno;
float mark[4],total;
char name[20];
public:
void getdetails();
void displaydetails();
};
void student::getdetails()
{
cout<<"enter the name";
cin>>name;
cout<<"enter the register number";
cin>>regno;
cout <<"enter 4 marks one by one"<<endl;
for(int i=0;i<4;i++)
{
cin>>mark[i];
total=total+mark[i];
}
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
101
void student::displaydetails()
{
cout<<"STUDENT DETAILSn";
cout<<"Name:"<<name<<endl;
cout<<"register number"<<regno<<endl;
for(int i=0;i<4;i++)
{
cout<<"Mark"<<i+1<<"="<<mark[i]<<endl;
}
cout<<"Total"<<total;
}
void main()
{
clrscr();
student s1;
s1.getdetails();
s1.displaydetails();
getch();
}
OUT PUT:
enter the name shaji
enter the register number 4
enter 4 marks one by one
mark1=78
mark2=90
mark3=100
mark4=79
total=347
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
102
2.PROGRAM USING STATIC CLASS MEMBER
#include<iostream.h>
#include<conio.h>
class test
{
int code;
static int count;
public:
void setcode(void)
{
code=++count;
}
void showcode(void)
{
cout<<"object number"<<code<<endl;
}
static void showcount(void)
{
cout<<"count"<<count<<endl;
}
};
int test::count;
void main()
{
clrscr();
test t1,t2;
t1.setcode();
t2.setcode();
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
103
test::showcount();
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
getch();
}
OUTPUT:
Count 2
Count 3
Object number 1
Object number 2
Object number 3
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
104
3.PROGRAM USING ARRAYS OF OBJECT
#include<iostream.h>
#include<conio.h>
class rec
{
private:
int i;
int b;
public:
rec(int a,int c)
{
i=a;
b=c;
}
void put()
{
cout<<"area is:"<<i*b<<endl;
}
};
void main()
{
clrscr();
rec obj[3]={rec(3,6),rec(2,5),rec(5,5)};
cout<<"displaying areas of rectangles:n";
for(int i=0;i<3;i++)
obj[i].put();
getch();
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
105
OUTPUT:
Displaying area of rectangle :
Area is:18
Area is:10
Area is:25
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
106
4 . OBJECT AS FUNCTION ARGUMENT
#include<iostream.h>
#include<conio.h>
class time
{
int hours;
int minutes;
public:
void gettime(int h, int m)
{
hours=h;
minutes=m;
}
void puttime()
{
cout<<hours<<"hours and";
cout<<minutes<<"mintues"<<"n";
}
void sum (time,time);
};
void time::sum(time t1,time t2)
{
minutes=t1.minutes+t2.minutes;
hours=minutes/60;
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
}
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
107
void main()
{
clrscr();
time t1,t2,t3;
t1.gettime(2,45);
t2.gettime(3,30);
t3.sum(t1,t2);
cout<<"t1=";t1.puttime();
cout<<"t2=";t2.puttime();
cout<<"t3=";t3.puttime();
getch();
}
OUTPUT:
T1=2hours and 45 minutes
T2=3hours and 30 minutes
T3=6hours and 15 minutes
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
108
5. OVER LOAD CONSTRUCTORS
#include<iostream.h>
#include<conio.h>
class cons
{
int a,b;
public:
cons()
{
cout<<"constructor with no argumentsn";
a=0;
b=0;
}
cons(int x,int y)
{
cout<<"n constructor with argumentsn";
a=x;
b=y;
}
cons(cons&c)
{
cout<<"n copy constructorn";
a=c.a;
b=c.b;
}
void display()
{
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
109
cout<<"a="<<a;
cout<<"tb="<<b;
}
};
void main()
{
clrscr();
cout<<"constructor overloadingn";
cons x;
x.display();
cons y(5,9);
y.display();
cons z(y);
z.display();
getch();
}
OUTPUT
Constructor overloading
Constructor with no arguments
a=0 b=0
Constructor with arguments
a=5 b=9
copy constructor
a=5 b=9
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
110
6 .PROGRAM IMPLEMENTING TWO DIMENSIONAL ARRAYS
#include<iostream.h>
#include<conio.h>
class matrix
{
int **p;
int d1,d2;
public:
matrix(int x,int y);
void getelement(int i,int j,int value)
{
p[i][j]=value;
}
int&putelement(int i,int j)
{
return p[i][j];
}
};
matrix::matrix(int x,int y)
{
d1=x;
d2=y;
p=new int*[d1];
for(int i=0;i<d1;i++)
p[i]=new int[d2];
}
void main()
{
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
111
clrscr();
int m,n;
cout<<"Enter the size of the matrix";
cin>>m>>n;
matrix A(m,n);
cout<<"n enter matrix elements row by row n";
int i,j,value;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
cin>>value;
A.getelement(i,j,value);
}
cout<<"n";
cout<<A.putelement(1,2);
getch()
OUTPUT:
Enter size of matrix 3 4
Enter matrix elements row by row
11 12 13 14
15 16 17 18
19 20 21 22
17
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
112
7.PROGRAM IMPLEMENTING DESTRUCTOR
#include<iostream.h>
#include<conio.h>
int count=0;
class alpha
{
public:
alpha()
{
count++;
cout<<"n No.of.objects created"<<count;
}
~alpha()
{
cout<<"n No.of.objects destroyed"<<count;
count--;
}
};
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
113
void main()
{
clrscr();
{
cout<<"n Enter main n";
alpha A1,A2,A3,A4;
{
cout<<"nn Enter block 1 n";
alpha A5;
}
{
cout<<"nn Enter block 2 n";
alpha A6;
}
cout<<"nn Re enter main n";
}
getch();
}
OUTPUT:
No.of object created 1
No of object created 2
No of object created 3
No of object created 4
Enter block 1
No of object created 5
No of object destroyed 5
Enter block 2
No of object created 5
No of object destroyed 5
Re enter main
No of object destroyed 4
No of object destroyed 3
No of object destroyed 2
No of object destroyed 1
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
114
8 . OVER LOAD OPERATORS
#include<iostream.h>
#include<conio.h>
class space
{
int x;
int y;
int z;
public:
void getdata(int a,int b,int c);
void display();
void operator -();
};
void space :: getdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void space :: display()
{
cout<<x<<"n";
cout<<y<<"n";
cout<<z<<"n";
}
void space ::operator-()
{
x=-x;
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
115
y=-y;
z=-z;
}
void main()
{
clrscr();
space s;
s.getdata(10,-20,45);
cout<<"s:";
s.display();
-s;
cout<<"s:";
s.display();
getch();
}
OUT PUT
S
10
-20
40
S
-10
20
-40
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
116
9.BINARY OPERATORS USING FRIEND FUNCTION
#include<iostream.h>
#include<conio.h>
class binary
{
int a,b;
public:
void get()
{
cout<<"give values";
cin>>a>>b;
}
void display()
{
cout<<a<<b<<"n";
}
friend binary operator-(binary u,binary v)
};
binary operator-(binary u,binary v)
{
binary s;
s.a=u.a-v.a;
s.b=u.b-v.a;
return(s);
}
void main()
{
MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided)
117
clrscr();
binary obj1,obj2,result;
obj1.get();
obj2.get();
result=obj1-obj2;
cout<<"input values";
obj1.display();
obj2.display();
cout<<"result";
result.display();
getch();
}
OUTPUT:
Give value 5 6
Give value 2 4
Input values 56
24
Result 34
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes
C++ Notes

More Related Content

What's hot

Presentation on class and object in Object Oriented programming.
Presentation on class and object in Object Oriented programming.Presentation on class and object in Object Oriented programming.
Presentation on class and object in Object Oriented programming.Enam Khan
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
Classes and Objects in C#
Classes and Objects in C#Classes and Objects in C#
Classes and Objects in C#Adeel Rasheed
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
Class objects oopm
Class objects oopmClass objects oopm
Class objects oopmShweta Shah
 
Friend functions
Friend functions Friend functions
Friend functions Megha Singh
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend classAbhishek Wadhwa
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming conceptsGanesh Karthik
 

What's hot (20)

Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
 
Presentation on class and object in Object Oriented programming.
Presentation on class and object in Object Oriented programming.Presentation on class and object in Object Oriented programming.
Presentation on class and object in Object Oriented programming.
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
class c++
class c++class c++
class c++
 
Class and object
Class and objectClass and object
Class and object
 
Classes and Objects in C#
Classes and Objects in C#Classes and Objects in C#
Classes and Objects in C#
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Class objects oopm
Class objects oopmClass objects oopm
Class objects oopm
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Friend functions
Friend functions Friend functions
Friend functions
 
C# Types of classes
C# Types of classesC# Types of classes
C# Types of classes
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
 
Write First C++ class
Write First C++ classWrite First C++ class
Write First C++ class
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend class
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 

Similar to C++ Notes (20)

chapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdfchapter-7-classes-and-objects.pdf
chapter-7-classes-and-objects.pdf
 
Class and object
Class and objectClass and object
Class and object
 
OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
 
oop lecture 3
oop lecture 3oop lecture 3
oop lecture 3
 
lecture3.pptx
lecture3.pptxlecture3.pptx
lecture3.pptx
 
object oriented programming language by c++
object oriented programming language by c++object oriented programming language by c++
object oriented programming language by c++
 
C++ classes
C++ classesC++ classes
C++ classes
 
My c++
My c++My c++
My c++
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
 
Object & classes
Object & classes Object & classes
Object & classes
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
 
ccc
cccccc
ccc
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
Chapter18 class-and-objects
Chapter18 class-and-objectsChapter18 class-and-objects
Chapter18 class-and-objects
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
 
4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 

Recently uploaded

Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonhttgc7rh9c
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of PlayPooky Knightsmith
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningMarc Dusseiller Dusjagr
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxakanksha16arora
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17Celine George
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 

Recently uploaded (20)

Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 

C++ Notes

  • 1. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 1 C Structure Revisited We known that one of the unique feature of the C language is structures. They provide a method for packing together data of different types. A structure is a convenient tool for handling a group of logically related data items. It is a user define data type with a template that serves to define its data properties. Once the structure type has been defined, we can create variables of that type using declaration that are similar to the built in type declaration.For example, consider the following declaration: struct student { char name[20]; int roll_number; float total_marks; }; The keyword struct declare student as a new data type that can hold three fields of different data types. These fields are known as structure member or elements. The identifier student, which is referred to as structure name or structure tag, can be used to create variables of type student. Example: struct student A; // C declaration A is a variable of type student and has three member variables as defined by the template. Member variable can be accessed using the dot or period operator as follows: strcpy(A.name, "John"); A.roll_number = 999; A.total_marks = 595.5; final_total = A.total_marks + 5; Structure can have arrays, pointer or structure as members. Limitations of structure: Important limitation of structures is that they do not permit data hiding. The only difference between a structure and a class in C++ is that, by default, the members of a class are private while, by default, the members of structures are public.
  • 2. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 2 Specifying a class: 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 build-in data type. Generally, a class specification has two parts: 1. Class declaration 2. Class function definitions The class declaration describes the type scope of its members. The class function definitions describe how the class functions are implemented. The general form of a class declaration is: class class_name { private: variable declaration; function declaration; public: variable declaration; function declaration; }; More about Classes Classes contain data members and member functions, and the access of these data members and variable depends on the access specifiers. Class's member functions can be defined inside the class definition or outside the class definition. Class in C++ is similar to structures in C, the only difference being, class defaults to private access control, where as structure defaults to public. All the features of OOPS, revolve around classes in C++. Inheritance, Encapsulation, Abstraction etc. Objects of class holds separate copies of data members. We can create as many objects of a class as we need.
  • 3. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 3 Objects Class is a blueprint or a template. No storage is assigned when we define a class. Objects are instances of class, which holds the data variables declared in class and the member functions work on these class objects. class Abc { int x; void display(){} //empty function }; int main() { Abc obj; // Object of class Abc created } Access Control in Classes: Now before studying how to define class and its objects, lets first quickly learn what are access specifiers. Access specifiers in C++ class define the access control rules. C++ has 3 new keywords introduced, namely, public private protected • These access specifiers are used to set boundaries for availability of members of class be it data members or member functions • Access specifiers in the program, are followed by a colon. You can use either one, two or all 3 specifiers in the same class to set different boundaries for different class members. They change the boundary for all the declarations that follow them. Public Public, means all the class members declared under public will be available to everyone. The data members and member functions declared public can be accessed by other classes too. Hence there are chances that they might change them. So the key members must not be declared public.
  • 4. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 4 class PublicAccess { public: // public access specifier int x; // Data Member Declaration void display(); // Member Function decaration } Private Private keyword, means that no one can access the class members declared private outside that class. If someone tries to access the private member, they will get a compile time error. By default class variables and member functions are private. class PrivateAccess { private: // private access specifier int x; // Data Member Declaration void display(); // Member Function decaration } Protected Protected, is the last access specifier, and it is similar to private, it makes class member inaccessible outside the class. But they can be accessed by any subclass of that class. class ProtectedAccess { protected: // protected access specifier int x; // Data Member Declaration void display(); // Member Function decaration } Defining Class and Declaring Objects When we define any class, we are not defining any data, we just define a structure or a blueprint, as to what the object of that class type will contain and what operations can be performed on that object.
  • 5. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 5 Below is the syntax of class definition, class ClassName { Access specifier: Data members; Member Functions(){} }; Here is an example, we have made a simple class named Student with appropriate members, class student { public: int rollno; string name; }; So its clear from the syntax and example, class definition starts with the keyword "class" followed by the class name. Then inside the curly braces comes the class body, that is data members and member functions, whose access is bounded by access specifier. A class definition ends with a semicolon, or with a list of object declarations. Example : class student { public: int rollno; string name; }A,B; Here A and B are the objects of class Student, declared with the class definition. We can also declare objects separately, like we declare variable of primitive data types. In this case the data type is the class name, and variable is the object. int main() { student A; student B;
  • 6. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 6 } Both A and B will have their own copies of data members. Simple Class Program: // Header Files #include <iostream> #include<conio.h> // Class Declaration class person { //Access - Specifier public: //Varibale Declaration char name[20]; int number; }; //Main Function void main() { // Object Creation For Class person obj; //Get Input Values For Object Varibales cout<<"Enter the Name :"; cin>>obj.name; cout<<"Enter the Number :"; cin>>obj.number; //Show the Output cout << obj.name << ": " << obj.number << endl; getch(); }
  • 7. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 7 Sample Output: Enter the Name :Riya Enter the Number :100 Riya: 100 Defining Member Functions in Classes Member functions are the functions, which have their declaration inside the class definition and works on the data members of the class. The definition of member functions can be inside or outside the definition of class. If the member function is defined inside the class definition it can be defined directly, but if its defined outside the class, then we have to use the scope resolution :: operator along with class name along with function name. If we define the function inside class then we don't not need to declare it first, we can directly define the function. Inside the class definition: class Cube { public: int side; int getVolume() { return side*side*side; //returns volume of cube } }; But if we plan to define the member function outside the class definition then we must declare the function inside class definition and then define it outside. outside the class definition: class Cube { public: int side; int getVolume(); }
  • 8. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 8 int Cube :: getVolume() // defined outside class definition { return side*side*side; } The main function for both the function definition will be same. Inside main() we will create object of class, and will call the member function using dot . operator. void main() { Cube C1; C1.side=4; // setting side value cout<< "Volume of cube C1 ="<< C1.getVolume(); } Making an Outside Function Inline One of the objectives of OOP is to separate the details of implementation from the class definition. It is therefore good practice to define the member functions outside the class. We can define a member function outside the class definition and still make it inline by just using the qualifier inline in the header line of the function definition. Example: class item { ...... ...... public: void getdata(int a,float b); }; inline void item :: getdata(int a,float b) { number=a; cost=b; }
  • 9. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 9 Nesting of Member Functions A member function of a class can be called only by an object of that class using a dot operator. However, there is an exception to this. A member function can be called by using its name inside another member function of the same class. This is known as nesting of member functions. Nesting of Member Function #include <iostream.h> #include<conio.h> class set { int m,n; public: void input(); void display(); int largest(); }; int set :: largest(void) { if(m >= n) return(m); else return(n); } void set :: input(void) { cout << "Input value of m and n"<<"n"; cin >> m>>n; } void set :: display(void) { cout << "largest value=" << largest() <<"n"; }
  • 10. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 10 int main() { set A; A.input(); A.display(); return 0; } The output of program would be: Input value of m and n 25 18 Largest value=25 Private Member Functions Although it is normal practice to place all the data items in a private section and all the function in public, some situations may require certain function to be hidden from the outside calls. Tasks such a deleting an account in a customer file, or providing increment to an employee are event of serious consequences and therefore the function handling such task should have restricted access. We can place these function in the private section. A private member function can only be called by another function that is a member of its class. Even an object cannot invoke a private function using the dot operator. Consider a class as defined below: class sample { int m; void read(void); public: void update(void); void write(void); }; if s1 is an object of sample, then s1.read (); // won’t work, objects cannot access private members However, the function read() can be called by the function update() to update the value of m. void sample :: update(void)
  • 11. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 11 { read(); // simple call; no objects used } Arrays within a Class An array is a user defined data type whose members are homogeneous Arrays are used to store huge volume of similar data types. arrays can be easily manipulated with the help of loops it can used as member variables in a class Example: #include<iostream.h> #include<conio.h> class student { int regno; float mark[4], total; char name[20]; public: void getdetails(); void displaydetails(); }; void student ::getdetails() { cout<<"Enter the name"; cin>>name; cout<<"Enter the Register number"; cin>>regno;; cout<<"Enter 4 marks one by one"<<endl; for(int i=0;i<4;i++) { cin>>mark[i]; total=total+mark[i]; }
  • 12. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 12 } void student :: displaydetails() { cout<<"STUDENT DETAILS n"; cout<<" Name :"<<name<<endl; cout<<" Register Number"<<regno<<endl; for(int i=0;i<4;i++) { cout<<"Mark"<<i+1<<"="<<mark[i]<<endl; cout<<"Total"<<total; } } void main() { clrscr(); student s1; s1.getdetails(); s1.displaydetails(); getch(); } Run Enter the name : Riya Enter the Register number : 35 Enter 4 marks one by one : 78 80 99 89
  • 13. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 13 Output STUDENT DETAILS Name : Riya Register number : 35 Mark 1 = 78 Mark 2 = 80 Mark 3 = 99 Mark 4 = 89 Total = 346 Memory allocation for objects When a class is declared, memory is not allocated to data members of the class. Thus, there exists a template, but data members cannot be manipulated unless the object is created. It is note that when an object of a particular class is created, memory is allocated to both of its data members and member function. This is partially true. When an object is created, memory is allocated only to its data members and not to member function. The member function are created and placed in the memory only once when they are defined in the class specifier. The member functions are the same for all objects, no separate space is allocated member functions when objects are created. However separate storage is allocated for each objects data member since they contain different values. The following figure illustrated the idea the objects contains separate memory
  • 14. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 14 Static data members: The static data members are data objects that are common to all the objects of a class. Characteristics: • It is initialized to 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. Object 2 Data 1 Data 2 . . Data m Object 3 Data 1 Data 2 . . Data m Object 1 Data 1 Data 2 . . Data m Function1() Function2() Function 3() . . Function n()
  • 15. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 15 Syntax: Class classname { …………………… Static datatype datamember; ……………………. }; Datatype classname :: datamember=initial value Example : static int count; int item :: count; Static variables are normally used to maintain values common to the entire class. For example, a static data membevor can be used as a counter that records the occurrences of all the objects. Program illustrates the use of a static data member. #include <iostream.h> #include<conio.h> class item { static int count; int number; public: void getdata(int a) { number = a; count ++; } void getcount(void)
  • 16. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 16 { cout << "Count: "; cout << count <<"n"; } }; int item :: count; void main() { item a,b,c; a.getcount(); b.getcount(); c.getcount(); a.getdata(100); b.getdata(200); c.getdata(300); cout << "After rea.gading data"<<"n"; a.getcount(); b.getcount(); c.getcount(); getch(); } The output of the program would be: Count: 0 Count: 0 Count: 0 After reading data Count: 3 Count: 3 Count: 3
  • 17. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 17 Static Member Functions Like static member variable, we can also have static member function. A member function that is declared static has the following properties: • A static function can have access to only static members declared in the class. • A static member function can be called the class name as follows: class-name :: function-name; #include<iostream.h> #include<conio.h> class test { int code; static int count; public : void setcode(void) { code= ++count; } void showcode(void) { cout<<"object number"<<code<<endl; } static void showcount(void) { cout<<"count"<<count<<endl; } };
  • 18. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 18 int test::count; void main() { clrscr(); test t1,t2; t1.setcode(); t2.setcode(); test::showcount(); test t3; t3.setcode(); test::showcount(); t1.showcode(); t2.showcode(); t3.showcode(); getch(); } OUTPUT Count 2 Count 3 Object number 1 Object number 2 Object number 3 Arrays of objects : C++ allows to create an array of any data type including user defined data types Thus an array of variables that are of the type class can also be defined. Such variables are called arrays of an objects. It is often used to handle group of object which reside contiguously in the memory. Syntax: Classname arrayname[size of the array]
  • 19. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 19 Conceptual Explanation: Consider the following class definition Class employee { Char name[30]; Float age; Public: Void getdata(); Void putdata(); }; The identifier employee is a user defined data type and can be used to create objects that releate to different categories of the employees for example employee manager[3]; employee foreman[15]; the array manager contains three objects (managers), namely,manager[0], manager[1] and manager[2], of type employee class. Similarly, the foreman array contains 15 objects (foreman). Example Program : #include<iostream.h> #include<conio.h> class rec { private: int i; int b; public: rec(int a,int c) {
  • 20. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 20 i=a; b=c; } void put() { cout<<"Area is : "<<i*b <<endl; } }; void main() { clrscr(); rec obj[3]={rec(3,6),rec(2,5),rec(5,5)}; cout<<"Displaying Areas of Rectangles : n"; for(int i=0;i<3;i++) obj[i].put(); getch(); } Objects as function Arguments : • Objects can be used as function arguments, by these arguments we can pass either the values of the object or address of the object. • An object can be used as a function argument by the following way A copy of the entire object is passed to the function Only the address of the object is transferred to the function Pass-by-value: The first method is called pass-by-value
  • 21. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 21 Since 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 the function. Pass-by-reference: The second method is called Pass-by-reference When address of the object is passed, the called function works directly on the actual object used in the call This means any changes made to the object inside the function will reflect the actual object. The pass by reference method is more efficient since it requires to pass only the address of the object and not the entire object. Syntax : If the function has no return value, the syntax is functionname(argument list); If the function has return value, the syntax is Objectname. functionname(argument list); Or Objectname=functionname(argument list); Example : #include<iostream.h> #include<conio.h> class time { int hours; int minutes; public : void gettime(int h,int m) { hours=h; minutes=m; } void puttime() {
  • 22. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 22 cout<<hours<<"hours and"; cout<<minutes<<"minutes"<''n"; } void sum(time,time); }; void time :: sum (time t1, time t2) { minutes=t1.minutes+t2.minutes; hours=minutes/60; minutes=minutes%60; hours=hours+t1.hours+t2.hours; } void main() { tiem t1,t2,t3; t1.gettime(2,45); t2.gettime(3,30); t3.sum(t1,t2); cout<<"t1=";t1.puttime(); cout<<"t2=";t2.puttime(); cout<<"t3=";t3.puttime(); getch(); } output: t1=2 hours and 45 minutes t1=3 hours and 30 minutes t1=6 hours and 15 minutes
  • 23. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 23 Friendly Functions: The main concept of object oriented programming are data hiding and data encapsulation. Whenever data objects are declared in a private or protected category of class, these members are restricted by accessing by non member function To solve this problem, a friend function can be declared to have an access these members The friend function is a non member function that allows the function to access private data One of the most common reason for using this function is to access two separate classes Syntax: Class classname { Private: ……………. ……………. Public: ……………. ……………. Friend return type nonmemberfunction name(argument list); }; Rules: The keyword friend can be used only inside the class More than one friend function can be declared in a class A function can be friend to more than one classes The friend function definition should not contain the scope operator #include<iostream.h> #include<conio.h> class base { int val1,val2; public: void get()
  • 24. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 24 { cout<<"Enter two values:"; cin>>val1>>val2; } friend float mean(base ob); }; float mean(base ob) { return float(ob.val1+ob.val2)/2; } void main() { clrscr(); base obj; obj.get(); cout<<"n Mean value is : "<<mean(obj); getch(); } Output: Enter two values: 10, 20 Mean Value is: 15
  • 25. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 25 Returning Objects: A function not only receive object as arguments but also can return them If a member function called by an object returns an object then it is called function returning objects The syntax used is similar to that of returning variables from function The return type of function is declared as the return object type Program : #include<iostream.h> #include<conio.h> class complex { float x; float y; public : void input(float real, float imag) { x=real; y=imag; } friend complex sum(complex,complex); void show(complex); }; complex sum(complex c1,complex c2) { complex c3; c3.x=c1.x+c2.x; c3.y=c1.y+c2.y; return(c3); } void complex :: show(complex c)
  • 26. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 26 { cout<<c.x<<"+j"<<c.y<<"n"; } void main() { complex a,b,c; a.input(3.1,5.65); b.input(2.75,1.2); c=sum(a,b) cout<<"a=";a.show(a); cout<<"b=";b.show(b); cout<<"c=";c.show(c); getch(); } Output: a=3.1+j5.65 b=2.75+j1.2 c=5.85+j6.85
  • 27. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 27 Important points in unit I : A class is an extension to the structure data type A class can have both variables and functions as members By default members of the class are private whereas that of structure are public Only the member functions can have access to the private data members and private functions. However the public members can accessed from the outside the class In c++, the class variables are called object. With objects we can access the public members of a class using dot(.) operator We can define a member function inside or outside the class. The difference between a member function and a normal function is that a member function uses a membership ‘identity label’ in the header to indicate the class to which it belongs. The memory space for objects is allocated when they are declared Space for member variables is allocated separately for each object, but no separate space is allocated for member functions A data members of a class can declared as a static and is normally used to maintain values comman to the entire class The static member variable must be defined outside the class A static member function can have access to the static members declared in the same class and be called using the class name A function is declared as a friend is not in the scope of the class to which it has been declared as friend. It has full access to the private members of the class
  • 28. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 28 UNIT II Constructor:- Constructor is used for initializing the values to the data members of the Class. Constructor is that whose name is same as name of class. Constructor gets automatically called when an object of class is created. Constructors never have a Return Type even void. Constructor are of o Default , o Parameterized and o Copy Constructors Syntax: class A { int x; public: A(); //Constructor }; While defining a constructor you must remember that the name of constructor will be same as the name of the class, and constructors never have return type. Constructors can be defined either inside the class definition or outside class definition using class name and scope resolution:: operator. class A { int i; public: A(); //Constructor declared }; A::A() // Constructor definition { i=1;
  • 29. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 29 } Characteristics of Constructors They should be declared in the public section They are automatically invoked and have no return types, neither can they return values They can not be inherited but called by Derived Class Constructor They can not be virtual nor can we refer to their addresses & they can have default arguments An object with constructor or destructor can’t member of union They make implicit calls to new and delete When constructor is declared, init becomes mandatory Default Constructor Default constructor is the constructor which doesn't take any argument. It has no parameter. Syntax : class_name () { Constructor Definition } Example : class Cube { int side; public: Cube() { side=10; } }; int main() { Cube c; cout << c.side; }
  • 30. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 30 Output : 10 In this case, as soon as the object is created the constructor is called which initializes its data members. A default constructor is so important for initialization of object members, that even if we do not define a constructor explicitly, the compiler will provide a default constructor implicitly. class Cube { int side; }; int main() { Cube c; cout << c.side; } Output : 0 In this case, default constructor provided by the compiler will be called which will initialize the object data members to default value, that will be 0 in this case. Example 2 : Default Constructor #include<iostream> #include<conio.h> class Example { // Variable Declaration int a,b; public: //Constructor Example() { // Assign Values In Constructor a=10; b=20; cout<<"Im Constructorn"; }
  • 31. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 31 void Display() { cout<<"Values :"<<a<<"t"<<b; } }; Void main() { Example Object; // Constructor invoked. Object.Display(); // Wait For Output Screen getch(); } Sample Output Im Constructor Values :10 20 Parameterized Constructor These are the constructors with parameter. Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as argument. Example : class Cube { int side; public: Cube(int x) { side=x; } };
  • 32. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 32 int main() { Cube c1(10); Cube c2(20); Cube c3(30); cout << c1.side; cout << c2.side; cout << c3.side; } OUTPUT : 10 20 30 By using parameterized constructor in above case, we have initialized 3 objects with user defined values. We can have any number of parameters in a constructor. Example 2: Definition In C++,Constructor is automatically called when object(instance of class) create.It is special member function of the class.Which constructor has arguments thats called Parameterized Constructor. • It has same name of class. • It must be a public member. • No Return Values. • Default constructors are called when constructors are not defined for the classes. Syntax: class class-name { Access Specifier: Member-Variables Member-Functions public: class-name(variables) { // Constructor code }
  • 33. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 33 ... other Variables & Functions } Example Program #include<iostream> #include<conio.h> class Example { // Variable Declaration int a,b; public: //Constructor Example(int x,int y) { // Assign Values In Constructor a=x; b=y; cout<<"Im Constructorn"; } void Display() { cout<<"Values :"<<a<<"t"<<b; } }; int main() { Example Object(10,20); // Constructor invoked. Object.Display(); // Wait For Output Screen getch(); return 0; }
  • 34. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 34 Sample Output In Constructor Values :10 20 Multiple Constructor in a class : (Constructor Overloading) Syntax class class-name { Access Specifier: Member-Variables Member-Functions public: class-name() { // Constructor code } class-name(variables) { // Constructor code } ... other Variables & Functions } Example Program #include<iostream> #include<conio.h> class Example { // Variable Declaration int a,b; public: //Constructor wuithout Argument
  • 35. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 35 Example() { // Assign Values In Constructor a=50; b=100; cout<<"nIm Constructor"; } //Constructor with Argument Example(int x,int y) { // Assign Values In Constructor a=x; b=y; cout<<"nIm Constructor"; } void Display() { cout<<"nValues :"<<a<<"t"<<b; } }; int main() { Example Object(10,20); Example Object2; // Constructor invoked. Object.Display(); Object2.Display(); // Wait For Output Screen getch(); return 0;
  • 36. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 36 } Sample Output In Constructor In Constructor Values :10 20 Values :50 100 Dynamic Initialization of Objects One Advantage Of Dynamic Initialization is that we can Provide Various initialization formats, using Overloaded Constructors. This Provides The Flexibility Of using different Formats of Data at run time Depending upon the situation //long-term fixed deposit system #include<iostream.h> class Fixed_deposit { long int P_amount; //principal amount int Years; //Period of investment float Rate; //Insert rate float R_value; //Return value of amount public: Fixed_deposit(){} Fixed_deposit(long int p, int y, float r=0.12); Fixed_deposit(long int p, int y, int r); void display(void); }; Fixed_deposit :: Fixed_deposit(long int p, int y, float r) { P_amount = p; Years = y; Rate = r;
  • 37. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 37 R_value = P_amount; for(int i =1; i<=y; i++) R_value = R_value * (1.0 + r); } Fixed_deposit :: Fixed_deposit(long int p, int y, int r) { P_amount = p; Years = y; Rate = r; R_value = P_amount; for(int i = 1; i<= y; i++) R_value = R_value*(1.0+float(r)/100); } void Fixed_deposit :: display(void) { cout<<"n" <<"Principal Amount = " <<P_amount <<"n" <<"Return Value = " <<R_value <<"n"; } int main() { Fixed_deposit FD1,FD2,FD3; //deposit created long int p; //principal amount int y; //investment period, years float r; //interest rate, decimal form int R; //interest rate, percent form cout<< "Enter amount, peroid, interset rate(in precent)"<<"n"; cin >> p >> y >> R; FD1 = Fixed_deposit(p,y,R); cout<< "Enter amount, peroid, interset rate(in decimal form)"<<"n"; cin >> p >> y >> r;
  • 38. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 38 FD2 = Fixed_deposit(p,y,r); cout<< "Enter amount and period"<<"/n"; cin >> p >> y; FD3 = Fixed_deposit(p,y); cout <<"nDeposit 1"; FD1.display(); cout <<"nDeposit 2"; FD2.display(); cout<<"nDeposit 3"; FD3.display(); return 0; } Output: Enter amount, period, interest rate (in percent) 10000 3 18 Enter amount, period, interest rate (in decimal form) 10000 3 0.18 Enter amount, period, interest rate (in percent) 10000 3 Deposit 1 Principal Amount =10000 Return Value = 16430.3 Deposit 2 Principal Amount =10000 Return Value = 16430.3 Deposit 1
  • 39. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 39 Principal Amount =10000 Return Value = 14049.3 Copy Constructor Copy Constructor is a type of constructor which is used to create a copy of an already existing object of a class type. It is usually of the form X (X&), where X is the class name. The compiler provides a default Copy Constructor to all the classes. Syntax of Copy Constructor class-name (class-name &) { . . . . } As it is used to create an object, hence it is called a constructor. And, it creates a new object, which is exact copy of the existing copy, hence it is called copy constructor. Copy Constructor: One Object Member Variable Values assigned to Another Object Member Variables is called copy constructor. Syntax class class-name { Access Specifier: Member-Variables Member-Functions public:
  • 40. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 40 class-name(variable) { // Constructor code } ... other Variables & Functions } Syntax : Argument In Main Function ClassName Object1(value); ClassName Object2=Object1; Example Program #include<iostream> #include<conio.h> class Example { // Variable Declaration int a,b; public: //Constructor with Argument Example(int x,int y) { // Assign Values In Constructor a=x; b=y; cout<<"nIm Constructor"; } void Display() { cout<<"nValues :"<<a<<"t"<<b; } };
  • 41. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 41 int main() { Example Object(10,20); //Copy Constructor Example Object2=Object; // Constructor invoked. Object.Display(); Object2.Display(); // Wait For Output Screen getch(); return 0; } Sample Output In Constructor Values :10 20 Values :10 20 Dynamic Constructor: The constructor 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 object are not of the same size, thus resulting in the saving of memory Allocation of memory to objects at the time of their construction is known as dynamic construction of objects This memory is allocated with the help of new operator Example : #include <iostream.h> #include <conio.h> class Account { private: int account_no; int balance;
  • 42. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 42 public : Account(int a,int b) { account_no=a; balance=b; } void display() { cout<< "nAccount number is : "<< account_no; cout<< "nBalance is : " << balance; } }; void main() { clrscr(); int an,bal; cout<< "Enter account no : "; cin >> an; cout<< "nEnter balance : "; cin >> bal; Account *acc=new Account(an,bal); //dynamic constructor acc->display(); //'->' operator is used to access the method getch(); } Output : Enter accountno : 121 Enter balance : 1000 Account number is : 121 Balance is :1000
  • 43. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 43 Constructing Two-dimensional Arrays: #include<iostream.h> #include<conio.h> class matrix { int **p; int d1,d2; public: matrix(int x,int y); void getelement(int i,int j,int value) { p[i][j]=value; } int &putelement(int i,int j) { return p[i][j]; } }; matrix :: matrix(int x,int y) { d1=x; d2=y; p=new int *[d1]; for(int i=0;i<d1;i++) p[i]=new int[d2]; } void main() { clrscr(); int m,n; cout<<"Enter the size of the matrix";
  • 44. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 44 cin>>m>>n; matrix A(m,n); cout<<"n enter matrix elements row by row n"; int i,j,value; for(i=0;i<m;i++) for(j=0;j<n;j++) { cin>>value; A.getelement(i,j,value); } cout<<"n"; cout<<A.putelement(1,2); getch(); } Output : Enter size of matrix 3,4 Enter matrix elements row by row 11 12 13 14 15 16 17 18 19 20 21 22 17 Const Keyword Constant is something that doesn't change. In C and C++ we use the keyword const to make program elements constant. Const keyword can be used in many context in a C++ program. Const keyword can be used with: • Variables • Pointers • Function arguments and return types • Class Data members • Class Member functions • Objects
  • 45. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 45 Const class Object When an object is declared or created with const, its data members can never be changed, during object's lifetime. Syntax : const class_name object; Const class Member function A const member function never modifies data members in an object. Syntax : return_type function_name() const; Example for const Object and const Member function class X { int i; public: X(int x) // Constructor { i=x; } int f() const // Constant function { i++; } int g() { i++; } }; Void main() { X obj1(10); // Non const Object const X obj2(20); // Const Object obj1.f(); // No error obj2.f(); // No error
  • 46. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 46 cout << obj1.i << obj2.i ; obj1.g(); // No error obj2.g(); // Compile time error getch() } Output : 10 20 Here, we can see, that const member function never changes data members of class, and it can be used with both const and non-const object. But a const object can't be used with a member function which tries to change its data members. Destructor : As we know that Constructor is that which is used for Assigning Some Values to data Members and For Assigning Some Values this May also used Some Memory so that to free up the Memory which is Allocated by Constructor, destructor is used which gets Automatically Called at the End of Program and we doesn’t have to Explicitly Call a Destructor and Destructor Cant be Parameterized or a Copy This can be only one Means Default Destructor which Have no Arguments. For Declaring a Destructor we have to use ~tiled Symbol in front of Destructor. Destructor is a special class function which destroys the object as soon as the scope of object ends. The destructor is called automatically by the compiler when the object goes out of scope. The syntax for destructor is same as that for the constructor, the class name is used for the name of destructor, with a tilde ~ sign as prefix to it. Syntax class A { public: ~A(); }; Destructors will never have any arguments. Example Program : #include<iostream.h> #include<conio.h>
  • 47. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 47 int count=0; class alpha { public: alpha() { count++ cout<<"n No of objects created"<<count; } ~alpha() { cout<<"n No of objects destroyed"<<count; } } void main() { cout<<"n Enter main n"; alpha A1,A2,A3,A4; { cout<<n n "Enter Block1 n"; alpha A5; } { cout<<n n "Enter Block2 n"; alpha A6; } cout<<n n "RE Enter MAINn"; getch(); } OUTPUT: No.of object created 1 No.of object created 2
  • 48. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 48 No.of object created 3 No.of object created 4 Enter Block 1 No.of object created 5 No.of object destroyed 5 Enter Block 2 No.of object created 5 No.of object destroyed 5 RE Enter MAIN No.of object destroyed 4 No.of object destroyed 3 No.of object destroyed 2 No.of object destroyed 1 Important points in unit II C++ provides special member function called the constructor, which enables on object to initialize itself when it is created. this is known as automatic initialization of objects. A constructor has the same name as that of a class. Constructors are normally used to initialize variables and to allocate memory. Similar to normal functions, constructors may be overloaded. When an object is created and initialized at the same time, a copy constructor gets called. We may make an object const if it does not modify any of it's data values. C++ also provides another member function called the destructor that destroys the objects when they are no longer required.
  • 49. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 49 UNIT-III OPERATOR OVERLOADING DEFINING OPERATOR OVERLOADING: Providing additional meaning to normal operator when they are applied to user defined data types. Compiler decides it as an over loaded operator not by looking as the data type. We use overloaded operator for user defined data type and normal operator for built-in data type. SYNTAX: Return data type operator symbol of operator (parameter) { //body of the function; } TYPES OF OPERATOR OVERLOADING: 1. Unary operator overloading. Takes one operand and no argument. 2. Binary operator overloading. Takes two operands and one argument. OPERATOR OVERLOADING CAN BE DONE WITH: 1. Overloading unary operator using normal member function: It takes one operand and no argument. 2. Overloading unary operator using friend function: It takes one operand and one argument. 3. Overloading binary operator using normal member function: It takes two operand and one argument. 4. Overloading binary operator using friend function: It takes two operand and two argument. OPERATORS THAT CAN’T OVERLOADED: 1. Scope resolution operator (::) 2. Pointer variable (*) 3. Dot operator (.)
  • 50. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 50 4. Conditional operator (?;) OVERLOADING UNARY OPERATORS: Unary operators take one operand and no argument. PROGRAM: #include<iostream.h> #include<conio.h> Class space { int x; int y; int z; public: void getdata (int a, int b, int c); void display(); void operator(); }; Void space::getdata (int a, int b, int c) { x=a; y=b; z=c; } void space::display() { cout<<x<<”t”; cout<<y<<”t”; cout<<z<<”t”; } Void space::operator-() {
  • 51. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 51 x=-x; y=-y; z=-z; } Void main() { space s; s.getdata(10,-20,30); cout<<”s:”; s.display(); -s; cout<<”s:”; s.display(); getch(); } OUTPUT: S = 10 -20 30 S = -10 20 -30 OVERLOADING BINARY OPERATORS: It takes two operands and one argument. PROBLEM ARISES: How 2 operands can be passed in a single argument. Example: t3 = t1+t2; t2 alone passed to operator function. PROGRAM: #include<iostream.h> #include<conio.h> Class binadd { int a,b; public: void getvalue()
  • 52. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 52 { cout<<”Enter the a,b values”; cin>>a>>b; } binadd operator+(binadd ob) { binadd t; t.a =a + ob.a; t.b =b + ob.b; return(t); } binadd operator-(binadd ob) { binadd t; t.a =a-ob.a; t.b=b-ob.b; return(t); } void display() { cout<<a<<b<<”n”; } }; void main() { clrscr(); binadd obj1,obj2,result,result1; obj1.getvalue(); obj2.getvalue(); result=obj1+obj2; result1=obj1-obj2; cout<<”Input values”;
  • 53. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 53 obj1.display(); obj2.display(); cout<<”Result”; result.display(); result1.display(); getch(); } OUTPUT: Enter the a,b values 1 2 Enter the a,b values 1 2 Input values 1 2 1 2 Result 2 4 0 0 OVERLOADING BINARY OPERATORS USING FRIEND FUNCTION: It takes two operand and two arguments. PROGRAM: #include<iostream.h> #include<conio.h> Class binary { int a,b; public: void get() { cout<<”Give values”; cin>>a>>b; } void display() {
  • 54. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 54 cout<<a<<b<<”n”; } friend binary operator-(binary u, binary v); }; Binary operator-(binary u, binary v) { binary s; s.a=u.a-v.a; s.b=u.b-v.b; return(subha); } void main() { clrscr(); binary obj1,obj2,result; obj1.get(); obj2.get(); result=obj1-obj2; cout<<”Input values”; obj1.display(); obj2.display(); cout<<”Result”; result.display(); getch(); } OUTPUT: Give values 10 20 Give values 5 10 Input values 10 20 5 10 Result
  • 55. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 55 5 10 RULES FOR OPERATOR OVERLOADING: 1. Only existing operators can be overloaded. New operator cannot be overloaded. 2. The overloaded operator must have atleast one operand that is of user defined data type. 3. We cannot change the basic meaning of an operator. That is to say, we cannot redefine the plus(+) operator to subtract one value from the other. 4. Overloaded operators follow the syntax rules of the original operators. They cannot be overridden. 5. There are some operators that cannot be overloaded like size of operator (size of), membership operator(.), pointer of member operator(*), scope resolution operator(::), conditional operator(?:). 6. We cannot use “friend” function to overload certain operators. However member function can be used to overload them. Friend functions cannot be used with assignment operator(=), function call operator(()), subscripting operator([]), class member access operator(->). 7. Unary operators overloaded by means of a member function take no explicit arguments and return no explicit values, but those overloaded by means of a friend function, take one reference argument. (the object of the relevant class) 8. Binary operator overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit arguments. 9. When using binary operators overloaded through a member function, the left hand operand must be an object of the relevant class. 10. Binary arithmetic operators such as +,-,*,/ must explicitly returns a value. They must not attempt to change their own argument. Program to perform string manipulation using operators #include<iostream.h> #include<conio.h> #include<stdio.h> #include<string.h> class string {
  • 56. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 56 protected: char str[25]; public: void getstring(); void display(); string operator+(string&); int operator==(string&); void operator=(string&); void operator+=(string&); }; void string::getstring() { cout<<"Enter string:"; gets(str); } string string::operator+(string &s) { string temp; if((strlen(str)+strlen(s.str))<25) { strcpy(temp.str,str); strcat(temp.str,s.str);
  • 57. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 57 } else { cout<<endl<<"concatenation is not possible"; } return temp; } int string::operator==(string &s) { return(strcmp(str,s.str)==0?1:0); } void string::operator=(string &s) { strcpy(str,s.str); } void string::operator+=(string &s) { strcat(str,s.str); } void string::display() { cout<<str;
  • 58. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 58 } void main() { string s1,s2,s3,s4; clrscr(); s1.getstring(); s2.getstring(); s3=s1+s2; cout<<endl<<"Concatenated string:"; s3.display(); if(s1==s2) cout<<endl<<"Comparison:Equal"; else cout<<endl<<"Comparison:Not equal"; cout<<endl<<"after addition:"; s1+=s2; s1.display(); s4=s3; cout<<endl<<"copy:"; s4.display(); s1=s2; getch();
  • 59. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 59 } Output: Enter string:Mohamed Enter string:Riyazudeen Concatenated string:MohamedRiyazudeen Comparison:Not equal After addition: MohamedRiyazudeen Copy: MohamedRiyazudeen Type Conversions: C++ has wide variety of data types ranging from the basic or primitive data types to the user defined data types. It is easier to convert same type of data from one to the other. For instance if we have two integer variables say Code: int num1, num2; The compiler will automatically convert them from one form to other if an equal’s sign is used between these two. For example Code: num1 = num2; will be automatically compiled by the compiler and no explicit logic needs to be embedded in the code. This is the case with basic data types. Now, come towards the user defined data types or what we call objects. In our article on operator overloading we explained how we can assign two variables of one user defined data types to each other. For example if we had class class1, we could create two objects of class1 like Code: class1 obj1, ob2;
  • 60. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 60 obj1=obj2 In that all the values from the variables of obj2 will be copied into the corresponding variables of obj1. In both of our examples we are storing values between variables of same data type. First we stored data from an integer to another integer and then we stored user defined objects of class1 to another object of class1. What if we want to store a float type data into an integer or an object of class1 into another object of class2 i.e. the data type of both of these objects will be different. Three types of situations might arise in the data conversion between uncompatible types 1. Conversion from basic type to class type 2. Conversion from class type to basic type. 3. Conversion from one class type to another class type. Conversion from basic to class type: Now let us consider another example for converting an int to a class type. class distance { private: int kilometers; int meters; public: distance(int meters) // constructor { kilometers = meters / 1000; meters = meters % 1000; } } The following conversion statements can be used in a function such as main: distance D1; // object D1 created int distance_covered = 10050; D1 = distance_covered; // int to class type After the execution of the 3rd statement, kilometers will hold the value 10 and meters will have the value 50.
  • 61. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 61 Thus, we see that the constructors used for the type conversion take a single argument whose type is to be converted Sample Program /* * Program that converts from miles to kilometers. * Illustrates type conversion from built-in types * to user-defined types. */ #include<iostream> using namespace std; class DistConv { private: int kilometers; double meters; const static double kilometersPerMile; public: // This function converts a built-in type (i.e. miles) to the user-defined type (i.e. Distconv) DistConv(double mile) // Constructor with one argument { double km = kilometersPerMile * mile ; // converts mile to Km kilometers = int(km); // converts float Km to int and assigns to kilometer meters = (km - kilometers) * 1000 ; // converts to meter } void display(void) { cout << kilometers << " kilometers and " << meters << " meters n" ; } }; // End of the Class Definition const double DistConv::kilometersPerMile = 1.609344; int main(void) {
  • 62. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 62 DistConv d1 = 5.0 ; // Uses the constructor with one argument cout << "5.0 miles = " ; d1.display( ) ; d1 = 2.0 ; // This form also uses the constructor with one argument cout << "2.0 miles = " ; d1.display( ) ; } Output 5.0 miles = 8 Kilometers and 46.72 meters 2.0 miles = 3 Kilometers and 218.688 meters Type Conversion – Class to Basic Type The constructor handles the task of converting basic types to class types very well. But you cannot use constructors for converting class types to basic data types. Instead, you can define an overloaded casting operator that can be used to convert a class data type into a basic data type. The general form of an overloaded casting operator function is shown below. This function is also known as a conversion function. Syntax: operator typename() { ----------- function body ----------- } The above function converts the class type into the typename mentioned in the function. For example, operator float( )converts a class type to float, operator int() converts a class type to int, and so on. The casting operator function should satisfy the following conditions: It must be a class member. It must not specify a return type. It must not have any arguments. The object that invokes this function has its members directly accessible since this is a member function.
  • 63. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 63 Sample Program /* * Program that converts between kilometers and miles. * Illustrates type conversion from a class type * to a built-in type. */ #include<iostream> class DistConv { private: int kilometers; double meters; nbsp; const static double kilometersPerMile; public: // This function converts a built-in type (i.e. miles) to the // user-defined type (i.e. DistConv) DistConv(double mile) // Constructor with one // argument { double km = kilometersPerMile * mile ; // converts miles to //kilometers kilometers = int(km); // converts float km to //int and assigns to kilometer meters = (km - kilometers) * 1000 ; // converts to meters } DistConv(int k, float m) // constructor with two // arguments { kilometers = k ;
  • 64. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 64 meters = m ; } // ********Conversion Function************ operator double() // converts user-defined type i.e. // DistConv to a basic-type { // (double) i.e. meters double K = meters/1000 ; // Converts the meters to &nsp; // kilometers K += double(kilometers) ; // Adds the kilometers return K / kilometersPerMile ; // Converts to miles } void display(void) { cout << kilometers << " kilometers and " << meters << " meters" ; } }; // End of the Class Definition const double DistConv::kilometersPerMile = 1.609344; int main(void) { DistConv d1 = 5.0 ; // Uses the constructor with one argument DistConv d2( 2, 25.5 ); // Uses the constructor with two arguments double ml = double(d2) ; // This form uses the conversion function // and converts DistConv to miles cout << "2.255 kilometers = " << ml << " milesn" ; ml = d1 ; // This form also uses conversion function // and converts DistConv to miles d1.display(); cout << " = " << ml << " milesn" ; } Output 2.255 kilometers = 1.25859 miles 8 kilometers and 46.72 meters = 5 miles
  • 65. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 65 Type Conversion – Class to Class Now that we have understood how to convert basic data types to class types and vice-versa, it is time to learn how to convert objects of one class type to another class type. The conversion between objects of different classes can be done using either a one- argument constructor or a conversion function. The choice depends upon whether the conversion routine has to be declared in the source class or in the destination class. To illustrate, consider a program that contains two classes: A and B. Also consider the statement: object_A = object_B; In the above statement, object_B of type B is converted to typeA and assigned to object_A. Therefore, object_B is the source and object_A is the destination. For the conversion, the user can use either a conversion function or a constructor with one argument, depending on whether it is specified in the source class or the destination class. In other words, if class B handles the conversion, it will hold a conversion function. On the other hand, if class A carries out the conversion, it will do that through a constructor that takes an argument of type class B. Note that only one of the two conversion routines should be specified; the compiler will yield an error if both are specified since it will not be able to figure out which routine to call. Sample Program /* * Program converts from one class type to * another using a conversion function * and a constructor */ #include <iostream> using namespace std; class Kilometers { private:
  • 66. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 66 double kilometers; public: Kilometers(double kilometers): kilometers(kilometers) {} void display() { cout << kilometers << " kilometeres"; } double getValue() { return kilometers; } }; class Miles { private: double miles; public: Miles(double miles) : miles(miles) {} void display() { cout << miles << " miles"; } operator Kilometers() { return Kilometers(miles*1.609344); } Miles(Kilometers kilometers) { miles = kilometers.getValue()/1.609344; } }; int main(void)
  • 67. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 67 { /* * Converting using the conversion function */ Miles m1 = 100; Kilometers k1 = m1; m1.display(); cout << " = "; k1.display(); cout << endl; /* * Converting using the constructor */ Kilometers k2 = 100; Miles m2 = k2; // same as: Miles m2 = Miles(k2); k2.display(); cout << " = "; m2.display(); cout << endl; } Output 100 miles = 160.934 kilometeres 100 kilometeres = 62.1371 miles
  • 68. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 68 Key Points: Operator overloading is one of the important feartures of C++ language. It is called compile time polymorphism. Using overloading feature we can add two user defined data types such as objects, with the same syntax, just as basic data types. We can overload almost all the C++ operators except the following: Class member access operators(.,.*) Scope resoulation operator(::) Size operator(sizeof) Conditional Operator(?:) The compiler does not support automatic type conversions for the user defiend data types. We use casting operator function to achieve this The casting operator function should satisfy the following conditions It must be a class member It must not specify a return type It must not have any arguments
  • 69. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 69 UNIT IV INHERITANCE: Inheritance is the process of creating new classes, called derived classes from an existing class, called base class. The derived class inherits all capabilities of the base class. It can also add some more features of this class. The base class is unchanged by its process. ADVANTAGES: 1. It permits reusability of the code. 2. Increases the reliability of the code. 3. It adds some enhancements to the base class. Inheritance is classified into the following forms: 1. Single Inheritance. 2. Multiple Inheritance. 3. Hierarchical Inheritance. 4. Multilevel Inheritance. 5. Hybrid Inheritance. DEFINING DERIVED CLASSES: A derived class is defined by specifying its relationship with the base class in addition to its own features. No memory is allocated to the declaration of a derived class, but memory is allocated when it is instantiated to create objects. SYNTAX: Class derived class:[visibility mode] base class { // Members of derived class and can access // Members of the base class }; Where derived class is the derived class name. Visibility mode is the inheritance type. It may be public or private. The default is private. Base class is the base class name. The Colon(:) indicates the derivation of derived class from the base class.
  • 70. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 70 The three possible styles of derivations are given below 1. Class A : Public D //public derivation { //members of A }; 2. Class A : private D { //members of A }; 3. Class A:D { //members of D }; When a base class is publicly inherited, public members of the base class become public members of the derived class and the protected members of the base class become protected members of the derived class. The table given below shows the visibility of class members Base class visibility Derived class visibility Public derivation Private derivation Private Not Inherited Not Inherited Protected Protected Private Public Public Private MAKING A PRIVATE MEMBER INHERITABLE: It is observed that a private member of a base class cannot be inherited and therefore it is not available for the derived class directly. To inherit the private data and functions, we have to convert the visibility modifier as either public or protected.A member declared as protected is accessible by the member functions within its class any class immediately derived from it. It cannot be accessed by the functions outside these two classes.
  • 71. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 71 A class can now use all the three visibility modes as illustrate here. Class sample { Private: //optional …………. //visible to member function within its class Protected: ………….. //visible to member functions of its own and derived class Public: …………… //visible to all functions in the program }; The various categories of functions which have access to the private and protected member could be 1. A member function of a class. 2. A member function of a derived class 3. A friend function of a class 4. A member function of a friend class The following table summarize the scope of access in various situations: Function Type Access directly to Private Protected Public Class Member Yes Yes Yes Derived Class Member No Yes Yes Friend Yes Yes Yes Friend class member Yes Yes Yes
  • 72. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 72 Single Inheritance In this type of inheritance one derived class inherits from only one base class. It is the most simplest form of Inheritance. Single Inheritance #include<iostream.h> #include<conio.h> class first //base or parent class { public: //Access Specifier int a,b; void getdata() //member function getdata() { cout<<"nEnter Number :::t"; cin>>a>>b; } void putdata() //member function putdata() { cout<<"nNumber Is :::t"<<a<<"t"<<b; } }; class second :public first //class second inherits property of class first { public : //Access Specifier int c; void add() { getdata();
  • 73. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 73 putdata(); c=a+b; cout<<"nnAnswer :::t"<<c; } }; int main() { clrscr(); second s1; //s1 is object of class second s1.add(); getch(); } Output: Enter Number ::: 10 50 Number is ::: 10 50 Answer ::: 60 Multiple Inheritance In this type of inheritance a single derived class may inherit from two or more than two base classes. Multiple Inheritance in c++ #include<iostream.h> #include<conio.h> class A // Base class 1 { public: int a; void First() { cout<<"nnFirst Number :::t"; cin>>a; } }; class B //Base class 2
  • 74. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 74 { public: int b; void second() { cout<<"nnSecond Number :::t"; cin>>b; } }; //Multiple Inheritance Level class C :public A,public B // Class C is derived class { public: int c; void result() { First(); second(); c=a+b; cout<<"nnResult :::t"<<c; } }; int main() { clrscr(); C c1; c1.result(); getch(); } Output: First Number ::: 40 Number is ::: 20 Answer ::: 60 Hierarchical Inheritance In this type of inheritance, multiple derived classes inherits from a single base class.
  • 75. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 75 Hierarchical inheritance in c++ #include<iostream.h> #include<conio.h> class A //Base Class { public: int a,b; void getnumber() { cout<<"nnEnter Number :::t"; cin>>a; } }; class B : public A //Derived Class 1 { public: void square() { getnumber(); //Call Base class property cout<<"nntSquare of the number :::t"<<(a*a); cout<<"nnt----------------------------------------------------"; } }; class C :public A //Derived Class 2 { public: void cube() { getnumber(); //Call Base class property cout<<"nntCube of the number :::t"<<(a*a*a); cout<<"nnt----------------------------------------------------"; }
  • 76. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 76 }; int main() { clrscr(); B b1; //b1 is object of Derived class 1 b1.square(); //call member function of class B C c1; //c1 is object of Derived class 2 c1.cube(); //call member function of class C getch(); } Output: Enter the Number 2 Square Number :::4 …………………………………………………… Enter the Number 3 Cube Number ::: 27 Multilevel Inheritance In this type of inheritance the derived class inherits from a class, which in turn inherits from some other class. The Super class for one, is sub class for the other. Multilevel Inheritance in c++ #include<iostream.h> #include<conio.h> class top //base class { public : int a; void getdata()
  • 77. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 77 { cout<<"nnEnter first Number :::t"; cin>>a; } void putdata() { cout<<"nFirst Number Is :::t"<<a; } }; //First level inheritance class middle :public top // class middle is derived_1 { public: int b; void square() { getdata(); b=a*a; cout<<"nnSquare Is :::"<<b; } }; //Second level inheritance class bottom :public middle // class bottom is derived_2 { public: int c; void cube() { square(); c=b*a; cout<<"nnCube :::t"<<c; } }; int main() { clrscr(); bottom b1; b1.cube(); getch(); } OUTPUT ENTER THE NUMBER ::: 4 SQUARE IS::: 16 CUBE IS ::: 64
  • 78. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 78 Hybrid (Virtual) Inheritance Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance. Hybrid inheritance is combination of two or more inheritances such as single, multiple, multilevel or Hierarchical inheritances. In the above program class B inherits property(member function) of class A which is base class and class D inherits property from class B and class C. #include<iostream.h> #include<conio.h> class A //Base class { public: int l; void len() { cout<<"nnLenght :::t"; cin>>l; //Lenght is enter by user } }; class B :public A //Inherits property of class A { public:
  • 79. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 79 int b,c; void l_into_b() { len(); cout<<"nnBreadth :::t"; cin>>b; //Breadth is enter by user c=b*l; //c stores value of lenght * Breadth i.e. (l*b) . } }; class C { public: int h; void height() { cout<<"nnHeight :::t"; cin>>h; //Height is enter by user } }; //Hybrid Inheritance Level class D:public B,public C { public: int res; void result() { l_into_b(); height(); res=h*c; //res stores value of c*h where c=l*b and h is height which is enter by user cout<<"nnResult (l*b*h) :::t"<<res; } }; int main() { clrscr(); D d1; d1.result(); getch(); } irtual Base Class: Why we need virtual base Class: we have already discussed on “Inheritance” that multiple inheritance is a process of creating a new classes which is derived from more than one base classes. Output: Length : : : 20 Breath : : : 30 Height : : : 40 Result (l*b*h) : ; : 24000
  • 80. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 80 Multiple inheritance hierarchies can be complex, which may lead to a situation in which a derived class inherits multiple times from the same indirect base class. For example the program segment given below illustrates how a base class can be derived twice from the derived class in different way. class A { protected: int x; ........... }; class B : public A { protected: ........... ........... }; class D :public A { protected: ................ ................ }; class abc : public B, public D { // the data member X comes twice ...................... ......................
  • 81. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 81 }; The data member X is inherited in the derived class abc, one through the derived class B and again through D. this is waste and confusing. The above multiple repetition of the data can be corrected by changing the derived class B and D into virtual base classes. Virtual Base Classes: Any base class which is declared using the keyword virtual is called a virtual base class. It is important to avoid unnecessary reputation of the same data member in the multiple inheritance hierarchies class A { protected: int x; ........... }; class B : virtual A { protected: ........... ........... }; class D :virtual A { protected: ................ ................ }; class abc : public B, public D { // the data member X comes only once
  • 82. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 82 ...................... ...................... }; By making B and D into virtual base classes for abc, a copy of the datamember X is available only once. A class may be both an ordinary and virtual base in the same inheritance structure #include<iostream.h> #include<conio.h> class student { int rno; public: void getnumber() { cout<<"Enter Roll No:"; cin>>rno; } void putnumber() { cout<<"nntRoll No:"<<rno<<"n"; } }; class test:virtual public student { public: int part1,part2; void getmarks() { cout<<"Enter Marksn"; cout<<"Part1:"; cin>>part1; cout<<"Part2:"; cin>>part2; } void putmarks() { cout<<"tMarks Obtainedn"; cout<<"ntPart1:"<<part1; cout<<"ntPart2:"<<part2; } };
  • 83. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 83 class sports:public virtual student { public: int score; void getscore() { cout<<"Enter Sports Score:"; cin>>score; } void putscore() { cout<<"ntSports Score is:"<<score; } }; class result:public test,public sports { int total; public: void display() { total=part1+part2+score; putnumber(); putmarks(); putscore(); cout<<"ntTotal Score:"<<total; } }; void main() { result obj; clrscr(); obj.getnumber(); obj.getmarks(); obj.getscore(); obj.display(); getch(); } Output: Enter Roll No: 200 Enter Marks Part1: 90 Part2: 80 Enter Sports Score: 80
  • 84. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 84 Roll No: 200 Marks Obtained Part1: 90 Part2: 80 Sports Score is: 80 Total Score is: 250 Abstract Class Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must provide definition to the pure virtual function, otherwise they will also become abstract class. Characteristics of Abstract Class Abstract class cannot be instantiated, but pointers and refrences of Abstract class type can be created. Abstract class can have normal functions and variables along with a pure virtual function. Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface. Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will become Abstract too. CONSTRUCTORS IN DERIVED CLASSES: The constructor play an important role in initializing an object’s data members and allocating required memory. The derived class need not have a constructor as long as the base has a no argument then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructor. The syntax for defining a constructor in a derived class is shown below. Derived class(arglist):Base 1(arglist)…………Base N(arglist M) { //body of the constructor of derived class }; EXAMPLE D (int a1, a2, float b1, float b2, int d1); A(a1, a2), /*call to constructor A*/ B (b1,b2), /*call to constructor B*/ { d=d1; //executes its own body }
  • 85. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 85 A(a1,a2) invokes the base constructor A() and B(b1,b2) invokes another base constructor B(). The constructor D() supplies the values for these four arguments. In addition it has one argument of its own. The constructor D() has a total of five arguments. D() may be invoked as follows. ………………………. D obj D (15, 72, 2.5, 17.54, 30); ………………………. These values are assigned to various parameters by the constructor D() as follows. 15 a1 72 a2 2.5 b1 17.54 b1 30 d1 The following table shows the order of invocation of constructors in a derived class. Method of inheritance Order of execution Class D:public B { ……………………… }; B() : base constructor D() : derived constructor Class D:public B1,public B2 { …………………. }; B1() : base constructor B2() : base constructor D() : derived constructor Class D1:public B1, virtual B2 { …………………… }; B2() : virtual base constructor B1() : base consructor D() derived constructor Class D1:public B { …………………………
  • 86. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 86 }; Class D2:public D1 { ………………………… }; B():super base constructor D1() : base constructor D2(): derived constructor MEMBER CLASSES – NESTING OF CLASSES When a class is declared and defined as a member of another class, it is known as a nested class. C++ allows to have an object of a class as a member of another class. When an object of a class is declared as a member of another class, it is called as container class. EXAMPLE Class C { …………. A a; B b; Public: C (arglist): a(arglist 1), b( arglist 2) { //constructor body } }; Arglist is the list of arguments that is to be supplied when C object is defined. These are used to initialize the members of C. Arglist1 & arglist2 may or may not use the arguments from arglist, a&b are function calls and therefore the argument do not contain the data types Key Points : The mechanism of deriving a new class from an old class is called inheritance. Inheritance provides the concept of reusability. The C++ classes can be reused using inheritance. A private member of class cannot be inherited either in public mode or private mode. A protected member inherited in public mode becomes protected, whereas inherited in private mode becomes private in the derived class. A public member inherited in public mode becomes public, whereas inherited in private mode becomes private in the derived class.
  • 87. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 87 The friend function and the member functions of a friend class can directly access the private and protected data. A class can contain object of other class. This is known as containership or nesting UNIT V INTRODUCTION A file is a collection of related information. A file is referred by its name. A file contains a collecting of related data stored in a particular area on the disk. The operating system provides most of the essential file manipulation services such as create, open, write, read, rewind, close and delete. A program invokes either or both of the following data communications. 1. Data transfer between the console unit and the program. 2. Data transfer between the program and a disk file. In C++ I/O system takes care of file operations. The file streams are moving between the disk and the program. The movement of data between the disk files and IO stream in a program is shown in below: Read Data Data Input Write Data Data Output The input stream supplies data to the program and the output stream receives data from the program. CLASSES FOR FILE STREAM OPERATIONS In C++ the I/O stream contains a set of classes to define the file handling methods. There are three classes for handling files. They are 1. ifstream - handling input files 2. ostream - handling output files 3. fstream - for both input&output files Input Stream Output Stream Disk Files Programs
  • 88. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 88 The actions performed by classes related to file management are given below: filebuf: Sets the file buffer to read and write. It contains openprot constant used in open() of file stream class and also contains close() as member. fstreambase: Supports operations common to the file streams. It is the base class for ifstream, ofstream and fstream classes. It contains open() and close() member functions. ifstream: Support input operations. It contains open() with default mode and inherits get(), getline(), read(), seekg() and tellg() functions from istream. ofstream: Supports output operations. It contains open() with default output mode and inherits put(), seekp(), tellp() and writer() functions from ostream. fstream: Supports I/O operations. It contains open() with default input mode and inherits all the functions from istream and ostream through iostream. OPENING AND CLOSING OF FILES In C++, a file can be opened in two ways 1. using constructors 2. using the function open() of the class After processing an operand file, it must be closed. It can be closed either by explicitly using the close() member function of the class or it is automatically closed by the destructor of the class, when the file stream object goes out of scope. 1. OPENING FILES USING CONSTRUCTORS Constructor is a member function. It initializes the objects. SYNTAX:
  • 89. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 89 Class objectname(value); Where class may be ofstream or ifstream objectname is the valid C++ variable variable is the string of characters within””. OPENING A OUTPUT FILE SYNTAX: Ofstream fileobject(“filename”); OPENING A INPUT FILE SYNTAX: Ifstream fileobject(“filename”); where ifstream is the class name fileobject is the input file object name filename is the input file to be created Example: ifstream employee(“emp.dat”); CLOSING A FILE All the opened files must be closed before the end of the program. SYNTAX fileobject.close(); Example: employee.close(); WRITING AND READING FILES To write data into the opened output file, the following syntax may be used. Fileobject<<data1<<data2<<………<<dataN; To read from the opened input file, the following syntax may be used. Fileobject>>data1>>data2>>……..dataN; Where Fileobject – is the file object name of the opened output/input file >>(or)<< - overloaded operator Data1, data2,…..dataN – data to write into the file or data to read from the file. PROGRAM Program to create a file student.out using constructor and writes student details into it. /*Student file, creating file with constructor*/
  • 90. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 90 #include<fstream.h> void main() { char name[30]; int marks; ofstream fout(“student.out”) cout<<”Enter Name:”; //read first students details cin>>name; cout<<”Enter marks secure:”; cin>>marks; fout<<name<<endl; //write to a file fout<<marks<<endl; cout<<”Enter Name:”; //read second student details cin>>name; cout<<”Enter marks secure:”; cin>>marks; fout<<name<<endl; //write to a file fout<<marks<<endl; } Output: Enter Name : Ajjai Enter Marks Secured : 95 Enter Name : Aravind Enter marks Secured : 90 Ajjai 95 Aravind 90 2.OPENING FILES USING OPEN() The function open() can be used to open multiple files that use the same stream object. To open an output file, the syntax is
  • 91. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 91 Ofstream fileobject: Fileobject.open(“filename”); Example: ofstream employee: employee.open(“emp.dat”); To open an input file, the syntax is: Ifstream fileobject; Fileobject.open(“filename”); DETECTING END OF FILES Detection of the end-of-file condition is necessary to prevent any further attempt to read data from file. This can be done in two ways. They are 1. using the member function “eof” 2. using objects USING MEMBER FUNCTION eof() is a member function of ios. It is used to detect the end of file condition. It returns non-zero value at the end of file condition is encountered and a zero otherwise. SYNTAX: Objectname.eof()!=0 Where object is the objectname used in the open command. USING OBJECTS Another indirect way for detecting the end-of-file conditions is that the file object itself has to be tested. It returns value of zero, if any error occurs in the file operation, including the end-of-file condition. If the eof condition is reached, it is considered as an error. Hence value 0 is returned. Thus the file object can be used to check the condition. SYNTAX: While(objectname) { …………………. ………………… } where objectname is the object name used in the open command.
  • 92. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 92 FILE MODES C++ provides a facility to open a file in different modes, in which case the argument must be explicitly passed. The table shows the list of file modes with mode value and their meaning Mode value Effect on the mode ios::in Open for reading ios::out Open for writing ios::ate File pointer goes to the end of file ios::app Open the file in append mode ios::trunk Truncate the file if it is already exist ios::nocreate Open fails if the file does not exist ios::noreplace Open fails if the file exists already ios::binary Open as a binary file The mode of the file must be specified at the time of opening. Its syntax are: (i)using constructor fstream fileobjectname(arg1, arg2); where fstream -classname fileobjectname-name of the object arg1 - name of the file to create in the disk. This should be within double quotes arg2 - flag/mode value Example fstream employee(“emp.dat”,ios::in); This opens the file in input mode. (ii)using member function Fstream fileobjectname; Fileobjectname.open(arg1, arg2) where fstream - class name fileobjectname- name of the object
  • 93. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 93 arg1 - name of the file to create in the disk. This should be within double quotes. arg2 - flag/ mode value. Example fstream student; employee.open(“emp.dat”, ios::app); This opens the file in append mode. FILE POINTERS AND THEIR MANIPULATION Each file object has two associated pointers known as file pointers. Some time it may be required to position the pointer of file at any place in the file or to know the current file position . In C++ there are two types of pointer. They are 1. Input pointer (or) get pointer 2. Output Pointer (or) put pointer The get pointer specifies a location from where the current reading operation is initiated. That is get pointer indicating the position for an input file The put pointer indicates the position for an output file. It specifies a location from wherse the current writing operation is initiated. Functions For Manipulation of File pointer. In C++ I/O system supports four functions for setting a file pointer to any desired position inside the file or to get current file pointer. It allows to control a position in the file where read/write operation takes place. 1. Seekg() 2. Seekp() 3. Tellg() 4. Tellp() i. seekg() It is member of class ifstream. It moves get file pointer to a specified location. It’s syntax is Where File_nameobject – name of the object Pos – byte number to move Filename_object.seekg(pos,flag);
  • 94. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 94 Flag – the position from to move This is optional The table given below shows the possible flags available Flag Meaning ios::beg Sets the pointer at the beginning of the file ios::cur Sets the pointer in the current position ios::end Sets the pointer at the end of the file Example : Fstream employee Employee.open(“employee.dat”,ios::in); Employee.seekg(10); When student .seekg(12) is executed, the get file pointer is moved to 12th byte from start ii. seekp() It is the member of the class ofstream. It moves put file pointer to specified position. Its syntax is Where File_nameobject – name of the object Pos – byte number to move Flag – the position from to move This is optional The table given below shows the possible flags available Flag Meaning ios::beg Sets the pointer at the beginning of the file ios::cur Sets the pointer in the current position ios::end Sets the pointer at the end of the file Example : Fstream employee Filename .object.seekp(ps,flag);
  • 95. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 95 Employee.open(“employee.dat”,ios::out); Employee.seekg(10); When student .seekg(12) is executed, the get file pointer is moved to 12th byte from start iii. tellg() It is the member class of ifstream. It returns the byte number of the current position of the get file pointer. It is syntax is Example : Fstream employee Employee.open(“employee.dat”,ios::in); Employee.seekg(12); Int p = employee.tellg(); When the above statements are executed 12 is assigned to p iv. tellp() it is member class of ofstream. It returns the byte number of the current position of the output pointer. The general form is Where File_nameobject - name of the object Var 1 - valid C++ variable Example : Fstream employee Employee.open(“employee.dat”,ios::out); Employee.seekg(12); Int p = employee.tellg(); When the above statements are executed 12 is assigned to p. SEQUENTIAL INPUT AND OUTPUT OPERATIONS Sequential input operations There are two member functions are available for sequential input operation. They are 1. get() 2. read() Int var 1 = filename_object.tellp(); Int var 1 = filename_object.tellg();
  • 96. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 96 1.get() The get() is a member function of the fstream class This function reads the file character by character and assigns it to the given character variable. Its syntax is File object name.get(variable); (ii) read() This read() function access data in binary form. It reads a block of binary data pointed by the get file pointer and assigns it to the pointer variable. Its syntax is file objectname.read(char*)&variable,size of (variable); where (char*)&variable - address of the character type variable. Sizeof(variable) - length of the variable in bytes. Sequential output operation 1. put() 2. write() (i)put() The put() function is used to write character by character into the file. Its syntax is file objectname.put(variable); (ii)write() The write() function used to write a block of binary data into the file. Its syntax is File objectname.write(char*)variable sizeof(variable); UPDATING A FILE : RANDOM ACCESS Updating is an usual task in the maintenance of any data file. Updating includes any one or more of the following. 1. Displaying the file contents 2. Modification of existing data 3. Adding a new data 4. Deleting an existing items The above actions requires movement of file pointer(get or put) from one position to another. This can be done easily by using the seek(), read() and write() functions.
  • 97. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 97 ERROR HANDLING DURING FILE OPERATIONS During the manipulations, the reading or writing operation any be failed due to the following. 1. Attempt to open a non-existing file in read-mode. 2. Try to open a read-only file in write mode. 3. Try to open a file with invalid name. 4. Insufficient disk space while writing to a file. 5. Try to access beyond the EOF. 6. Attempt to perform an unopened file. 7. Stream object created but not connected to a file. 8. Disk error during reading or writing operations. Such situation must be detected while accessing files and necessary action should be taken to access the file without error. Every stream (ifstream, ofstream and fstream) has a state associated with it. Errors and understand conditions are handled by setting and testing this state. The ios class supports several function to access the status recorded in the data member io-state. The following table shows the Error handling functions and their return values. FUNCTION MEANING OF RETURNS VALUE eof() It is used to check the end of file. It returns 1 if EOF is encountered while reading otherwise returns 0. fail() It is used to inform the failures in input or output operation. It returns 1 if read or write operation has failed otherwise returns 0. bad() It is used to check for unrecoverable errors. It returns 1 if an invalid operation is attempted or any unrecoverable errors, occurs returns 0. Otherwise, however it can be recovered. good() It is used to check whether the file is having any errors. It returns 1 if there is no error i.e., above all the functions are false. The following examples illustrates checking errors during the operations. 1.opening a non-existent file in read mode Ifstream infile(“my file”): If (linfile) {
  • 98. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 98 //file does not exist } 2.open fail : opening read-only file Ofstream outfile (“my file”); If (linfile) // or if(infile.bad()) { //file exist already and marked as read only } 3.invalid file name Infile open(“-*”); { //invalid file name } 4.read fail Infile.read(…); In(infile.bad()) { //file cannot be accessed further } 5.processing unopened file Infile.read(…); If(infile.fail()) { //file is not opened }
  • 99. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 99 COMMAND LINE ARGUMENTS Command line arguments are arguments that allows parameters to be passed to main() from shell prompt. There are two arguments available. They are 1. argc - it is an integer variable 2. argr - it is an array of pointers to characters. For instance, Main(int argc, char*argv[]) The first argument argc(known as argument counter)represents the number of arguments in the command line. The second argument argv(known as argument vector) is an array of char type pointers that point to the command line arguments. The size of the array will be equal to the value of argc. Suppose our program is sample, if we execute the file in the command prompt as c:>sample file1 file2 file3 then the value of argc would be 4 and the argv would be array of 4 pointer to string as argv[0] -> sample(always represents the command name) argv[1] -> file1 argv[2] -> file2 argv[3] -> file3
  • 100. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 100 PRACTICAL PROGRAMS WITH OUTPUT 1. PROGRAM USING ARRAYS WITHIN ACLASS #include<iostream.h> #include<conio.h> class student { int regno; float mark[4],total; char name[20]; public: void getdetails(); void displaydetails(); }; void student::getdetails() { cout<<"enter the name"; cin>>name; cout<<"enter the register number"; cin>>regno; cout <<"enter 4 marks one by one"<<endl; for(int i=0;i<4;i++) { cin>>mark[i]; total=total+mark[i]; } }
  • 101. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 101 void student::displaydetails() { cout<<"STUDENT DETAILSn"; cout<<"Name:"<<name<<endl; cout<<"register number"<<regno<<endl; for(int i=0;i<4;i++) { cout<<"Mark"<<i+1<<"="<<mark[i]<<endl; } cout<<"Total"<<total; } void main() { clrscr(); student s1; s1.getdetails(); s1.displaydetails(); getch(); } OUT PUT: enter the name shaji enter the register number 4 enter 4 marks one by one mark1=78 mark2=90 mark3=100 mark4=79 total=347
  • 102. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 102 2.PROGRAM USING STATIC CLASS MEMBER #include<iostream.h> #include<conio.h> class test { int code; static int count; public: void setcode(void) { code=++count; } void showcode(void) { cout<<"object number"<<code<<endl; } static void showcount(void) { cout<<"count"<<count<<endl; } }; int test::count; void main() { clrscr(); test t1,t2; t1.setcode(); t2.setcode();
  • 103. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 103 test::showcount(); test t3; t3.setcode(); test::showcount(); t1.showcode(); t2.showcode(); t3.showcode(); getch(); } OUTPUT: Count 2 Count 3 Object number 1 Object number 2 Object number 3
  • 104. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 104 3.PROGRAM USING ARRAYS OF OBJECT #include<iostream.h> #include<conio.h> class rec { private: int i; int b; public: rec(int a,int c) { i=a; b=c; } void put() { cout<<"area is:"<<i*b<<endl; } }; void main() { clrscr(); rec obj[3]={rec(3,6),rec(2,5),rec(5,5)}; cout<<"displaying areas of rectangles:n"; for(int i=0;i<3;i++) obj[i].put(); getch(); }
  • 105. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 105 OUTPUT: Displaying area of rectangle : Area is:18 Area is:10 Area is:25
  • 106. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 106 4 . OBJECT AS FUNCTION ARGUMENT #include<iostream.h> #include<conio.h> class time { int hours; int minutes; public: void gettime(int h, int m) { hours=h; minutes=m; } void puttime() { cout<<hours<<"hours and"; cout<<minutes<<"mintues"<<"n"; } void sum (time,time); }; void time::sum(time t1,time t2) { minutes=t1.minutes+t2.minutes; hours=minutes/60; minutes=minutes%60; hours=hours+t1.hours+t2.hours; }
  • 107. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 107 void main() { clrscr(); time t1,t2,t3; t1.gettime(2,45); t2.gettime(3,30); t3.sum(t1,t2); cout<<"t1=";t1.puttime(); cout<<"t2=";t2.puttime(); cout<<"t3=";t3.puttime(); getch(); } OUTPUT: T1=2hours and 45 minutes T2=3hours and 30 minutes T3=6hours and 15 minutes
  • 108. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 108 5. OVER LOAD CONSTRUCTORS #include<iostream.h> #include<conio.h> class cons { int a,b; public: cons() { cout<<"constructor with no argumentsn"; a=0; b=0; } cons(int x,int y) { cout<<"n constructor with argumentsn"; a=x; b=y; } cons(cons&c) { cout<<"n copy constructorn"; a=c.a; b=c.b; } void display() {
  • 109. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 109 cout<<"a="<<a; cout<<"tb="<<b; } }; void main() { clrscr(); cout<<"constructor overloadingn"; cons x; x.display(); cons y(5,9); y.display(); cons z(y); z.display(); getch(); } OUTPUT Constructor overloading Constructor with no arguments a=0 b=0 Constructor with arguments a=5 b=9 copy constructor a=5 b=9
  • 110. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 110 6 .PROGRAM IMPLEMENTING TWO DIMENSIONAL ARRAYS #include<iostream.h> #include<conio.h> class matrix { int **p; int d1,d2; public: matrix(int x,int y); void getelement(int i,int j,int value) { p[i][j]=value; } int&putelement(int i,int j) { return p[i][j]; } }; matrix::matrix(int x,int y) { d1=x; d2=y; p=new int*[d1]; for(int i=0;i<d1;i++) p[i]=new int[d2]; } void main() {
  • 111. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 111 clrscr(); int m,n; cout<<"Enter the size of the matrix"; cin>>m>>n; matrix A(m,n); cout<<"n enter matrix elements row by row n"; int i,j,value; for(i=0;i<m;i++) for(j=0;j<n;j++) { cin>>value; A.getelement(i,j,value); } cout<<"n"; cout<<A.putelement(1,2); getch() OUTPUT: Enter size of matrix 3 4 Enter matrix elements row by row 11 12 13 14 15 16 17 18 19 20 21 22 17
  • 112. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 112 7.PROGRAM IMPLEMENTING DESTRUCTOR #include<iostream.h> #include<conio.h> int count=0; class alpha { public: alpha() { count++; cout<<"n No.of.objects created"<<count; } ~alpha() { cout<<"n No.of.objects destroyed"<<count; count--; } };
  • 113. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 113 void main() { clrscr(); { cout<<"n Enter main n"; alpha A1,A2,A3,A4; { cout<<"nn Enter block 1 n"; alpha A5; } { cout<<"nn Enter block 2 n"; alpha A6; } cout<<"nn Re enter main n"; } getch(); } OUTPUT: No.of object created 1 No of object created 2 No of object created 3 No of object created 4 Enter block 1 No of object created 5 No of object destroyed 5 Enter block 2 No of object created 5 No of object destroyed 5 Re enter main No of object destroyed 4 No of object destroyed 3 No of object destroyed 2 No of object destroyed 1
  • 114. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 114 8 . OVER LOAD OPERATORS #include<iostream.h> #include<conio.h> class space { int x; int y; int z; public: void getdata(int a,int b,int c); void display(); void operator -(); }; void space :: getdata(int a,int b,int c) { x=a; y=b; z=c; } void space :: display() { cout<<x<<"n"; cout<<y<<"n"; cout<<z<<"n"; } void space ::operator-() { x=-x;
  • 115. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 115 y=-y; z=-z; } void main() { clrscr(); space s; s.getdata(10,-20,45); cout<<"s:"; s.display(); -s; cout<<"s:"; s.display(); getch(); } OUT PUT S 10 -20 40 S -10 20 -40
  • 116. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 116 9.BINARY OPERATORS USING FRIEND FUNCTION #include<iostream.h> #include<conio.h> class binary { int a,b; public: void get() { cout<<"give values"; cin>>a>>b; } void display() { cout<<a<<b<<"n"; } friend binary operator-(binary u,binary v) }; binary operator-(binary u,binary v) { binary s; s.a=u.a-v.a; s.b=u.b-v.a; return(s); } void main() {
  • 117. MOHAMED RIYAZUDEEN DEPARTMENT OF COMPUTER SCIENCE (Unaided) 117 clrscr(); binary obj1,obj2,result; obj1.get(); obj2.get(); result=obj1-obj2; cout<<"input values"; obj1.display(); obj2.display(); cout<<"result"; result.display(); getch(); } OUTPUT: Give value 5 6 Give value 2 4 Input values 56 24 Result 34