Magic of Thinking Big and Thinking Capacity
Magic of Thinking Big and Thinking Capacity
SYLLABUS
Semester III
L T P C
16CCU302 OBJECT ORIENTED PROGRAMMING WTIH C++ 4 - - 4
Course Objective
Learning Outcomes
UNIT I
UNIT II
Tokens, Expressions and Control Structures – Tokens – Keywords – Identifiers – Basic &
User – Defined Data Types – Operators in C++ - Operator Over Loading – Operator
Precedence – Control Structures – Functions in C++ - The Main Function – Function
UNIT III
UNIT IV
UNIT V
Suggested Readings:
Text Book:
1. Balagurusamy, E. (2013). Object Oriented Programming With C++, 6th edition, New
Delhi: Tata McGraw Hill Publishing Company Ltd.
Reference Books :
Website
W1: http://www.hscripts.com
W2: http://www3.ntu.edu
W3: http://www.bcanotes.com
W4: http://www.ddegjust.ac.in
UNIT-I
Lecture
Sl Support
Duration Topics to be Covered
No. Materials
(Hour)
PRINCIPLES OF OBJECT ORIENTED
PROGRAMMING T:4-7
1 1
Introduction and Evolution of OOP’s R2:1-3
Benefits of OOPs
Objects
4 1 Classes
Data abstraction and Encapsulation
Inheritance R2:6-11
Benefits of OOPs
Polymorphism
5 1 Dynamic binding
Message passing
UNIT – II
Lecture
Sl Support
Duration Topics to be Covered
No. Materials
(Hour)
Tokens ,Expressions and Control Structures T:35-49
1 1
Tokens, Keywords, Identifiers
Basic and User Defined Data Types R2:32-38
2 1 Variable Declaration W3
Variable Initialization
Operators
Operators in C++ T:49-64
3 1
Operator Overloading R2:46-66
W2
Operators
4 1
Operator Precedence
Control Structures Decision
5 1 If & If-Else Statements T:64-69
Jump Statements R2:112-159
R1:124-138
Control Structures Decision
6 1 Goto Statements
Break Statements
Looping R!:185-210
Switch case Statements W1
7 1
Do-While Statements
8 1 For Statements W3
Functions in C++ T:77-90
The main Function R2:179-185
9 1
Function Prototyping
Functions in C++
10 1
Call by Reference, Return by Reference
R3:273-275
Inline Functions
11 1
12 1 Functions in C++
Function Overloading
Recapitulation Important Questions
Discussion
Total No .Of Hours 12 HOURS
UNIT – III
Lecture
Sl Support
Duration Topics to be Covered
No. Materials
(Hour)
CLASSES AND OBJECTS
1 1 Introduction
Specifying a Class T:96-119
2 1 Defining Member Functions
Nesting of Member Functions R2:298-423
3 1
W2
4 1 Arrays within a Class
W3
Static Data Members R3:326-362
5 1
Static Member Function W2
6 1 Private Member Functions
Array of Objects T:119-135
7 1
Objects as Function Arguments
Friendly Functions R!:185-210
8 1
Pointers to Members W1
Constructors and Destructors T:144-164
9 1
Constructors
Copy Constructor R2:455-476
10 1 Dynamic Constructor W4
UNIT – IV
Lecture
Sl Support
Duration Topics to be Covered
No. Materials
(Hour)
Operator overloading T:171-186
1 1 R3:571-669
Type Conversion –Introduction
2 1 Defining Operator Overloading W2
Overloading unary and binary operator
3 1
Overloading binary operator using friends
4 Manipulation String using Operators T:186-195
1
R2:518-524
W3
Rules for Operator Overloading
5 1
Type Conversions
Inheritance: T:202-232
1
6 Extending Classes
Defining Derived Classes
1 Single Inheritance R2:538-548
7
8 1 Multilevel Inheritance
Multiple Inheritance W3
9 1
Hierarchical Inheritance W4
10 1 Hybrid Inheritance
Virtual Base Classes R3:708
11 1
Abstract Classes W4
Recapitulation
12 1
Important Questions Discussion
Total No .Of Hours 12 HOURS
UNIT – V
Lecture
Sl Support
Duration Topics to be Covered
No. Materials
(Hour)
Pointers, Virtual Functions and Polymorphism
1 1
Pointers- Introduction
2 1 Pointers to Objects
T:251-343
Pointers to Derived Classes
3 1
4 1 Virtual Functions
Working with Files R3:841-856
5
1 Introduction
Classes for File Stream Operations
6 1 Opening and Closing File
R2: 638-645
1 File Pointers
7 W2
Recapitulation
10 1 Important Questions Discussion
ESE Question Paper Discussions
11 1 Previous ESE Question Paper Discussions
12 1 Previous ESE Question Paper Discussions
Total No .Of Hours 12 HOURS
Suggested Readings:
TEXT BOOK
1. Balagurusamy, E. (2013). Object Oriented Programming With C++, 6th edition,
New Delhi: Tata McGraw Hill Publishing Company Ltd.
REFERENCE BOOKS
1. BjarneStroustroup. (2014). Programming -- Principles and Practice using
C++, 2nd Edition, Addison-Wesley.
2. BjarneStroustrup,. (2013). The C++ Programming Language, 4th Edition,
Addison- Wesley.
3. Paul Deitel, Harvey Deitel. (2011). C++ How to Program, 8th Edition,
Prentice Hall.
4. D.Ravichandran. (2010). Programming with C++.3rd Edition.. New Delhi:
Tata McGraw Hill Publishing Company Ltd.
Website
W1: http://www.hscripts.com
W2: http://www3.ntu.edu
W3: http://www.bcanotes.com
W4: http://www.ddegjust.ac.in
UNIT I
Unit 1
Introduction
Object-Oriented Programming (OOP) is the term used to describe a
programming approach based on objects and classes. The object-oriented
paradigm allows us to organize software as a collection of objects that consist
of both data and behaviour. This is in contrast to conventional functional
programming practice that only loosely connects data and behaviour.
Procedure-Oriented Programming
Features of POP
1. Mainly focused on writing the algorithms.
2. Most function uses Global data for sharing which are accessed freely
from function to function in the system.
3. POP follows the top down approach in program design.
4. It does not have data hiding options.
5. Functions transform data from one form to another.
6. Data can be moved openly from one function to another around the
system.
7. Sub-division of large program into smaller programs called functions.
8. Overloading process is not applicable in POP.
Objects
Classes
Data abstraction and Encapsulation
Inheritance
Polymorphism
Dynamic binding
Message passing
Objects:
The set of activities that the object performs defines the object's behavior.
For example, the hand can grip something or a Student (object) can give
the name or address.
Classes:
A class is the blueprint from which the individual objects are created.
Inheritance
The base class provides the property the derived class receives the
property.
This is the most common and most natural and widely accepted way of
implement this relationship.
Polymorphism
Polymorphism is the process taking more then one form.
More precisely Polymorphisms mean the ability to request that the same
operations be performed by a wide range of different types of things.
The method overloading is the ability to define several methods all with
the same name.
Dynamic binding
Dynamic binding is the process of resolving the function to be associated
with the respective functions calls during their runtime rather than
compile time.
Message passing
Every data in an object in oops that is capable of processing request
known as message.
All objects can communicate with each other by sending message to each
other
Message passing, also known as interfacing, describes the
communication between objects using their public interfaces.
Benefits of OOP
Applications of OOPs
For Develop Graphical related application like computer and mobile
games.
To evaluate any kind of mathematical equation use C++ language.
C++ Language are also used for design OS. Like window xp.
Google also use C++ for Indexing
Few parts of apple OS X are written in C++ programming language.
Internet browser Firefox are written in C++ programming language
All major applications of adobe systems are developed in C++
programming language. Like Photoshop, ImageReady, Illustrator and
Adobe Premier.
Some of the Google applications are also written in C++, including Google
file system and Google Chromium.
C++ are used for design database like MySQL.
C++ Statements
Preprocessor directives
A preprocessor directive begins with the character #. This must either be the
first character of the line or the first character of the line after some leading
whitespace.
Comments
Comments may be of the form:
// Comment \n
(Or)
/* comment */
The first form allows a trailing comment on a single line, while the second
form allows comments that span multiple lines.
Comments may appear anywhere.
Declarations
Prepared by Dr.S.Hemalatha, Department of Commerce (Computer Application), KAHE
11/14
Concepts of Object Oriented Programming 2016 – 2019 Batch
Function Declarations
void type identifier (formal_argument_list )
{
function_body
}
Executable statements
equivalent to:
switch ( expression )
declarations
...
default: statement
break;
continue;
return;
return expression;
goto statement_label;
statement_label: executable_statement
_____________________________________________________________
PART A (1 Mark)
(Online Examination)
PART B (2 Marks)
1. Define Objects
2. What is C++ Statements
3. List out the Basic Concepts of Oops
4. Specify object Oriented Languages
5. List out Applications of Oops
6. List out Applications of OOPs
7. What is Structure of C++ Program
8. Differentiate between POP and OOPs
9. What is Procedure Oriented Programming
10. What is Object Oriented Programming
11. What is C++ statements
12. What is data abstraction
13. Write any four features of OOPS
PART C (6 Marks)
UNIT II
Tokens, Expressions and Control Structures – Tokens – Keywords – Identifiers – Basic &
User – Defined Data Types – Operators in C++ - Operator Over Loading – Operator Precedence
– Control Structures – Functions in C++ - The Main Function – Function Prototyping – Call By
Reference – Return By Reference – In Line Functions – Function Over Loading – Friend and
Virtual Functions.
Unit – II
Tokens:
Smallest unit of a Program is called Token.
Keywords
Identifiers
Constants
Strings
Operators
Special Symbols
Keywords
Keywords are reserved words.
Has its predefine meaning.
C++ consist of c keywords and additional keywords of its own
Keyword List:
asm auto bool break
case catch char Class
const const_cast continue Default
delete do double dynamic_cast
else enum explicit Export
extern false float For
friend goto if Inline
int long mutable Namespace
new operator private Protected
public register reinterpret_cast Return
Short signed sizeof static
static_cast struct switch template
This throw true try
typedef typeid typename Union
unsigned using virtual Void
Data Types:
Data Type
Integer Type : Integer data type are like whole numbers, they also include
negative numbers but does not support decimal numbers.
Storage
Type Value range
size
unsigned
2 bytes 0 to 65,535
short
Float-point Type : Float data type allows user to store decimal values in a
variable.
Character Type : Character data type is used to store only one letter, digit,
symbol at a time.
Reference Types
Array : Array is a collection of similar data type. A single variable can hold only
one value at a time, If we want a variable to store more than one value of same
type we use array.
Variables
Variables are used to store values. variable name is the name of memory
location where value is stored. It must be alphanumeric, only underscore is
allowed in a variable name. It is composed of letters, digits and only
underscore. It must begin with alphabet or underscore. It cannot be begin with
numeric.
Declaration of Variable
Declaration will allocate memory for specified variable with garbage value.
Syntax :
Data-Type Variable-name;
Examples :
int a;
float b;
char c;
Variable (Identifiers):
Identifiers are user define name space
It change its value during the execution of the program
It refers the names of variables, functions, arrays, classes, etc
Rules:
1. Only alphabetic characters, digits and underscores are permitted.
2. Cannot start with digits.
3. Uppercase and lowercase are distinct
4. Keyword should not be as a variable name.
Example:
A, welcome
Initialization of Variable
Examples :
a = 10;
b = 4.5;
c = 'a';
Constants:
It does not change its value during the execution of the program
Example:
5,’a’,”welcome”
C++ Constants
Operators:
Arithmetic operators
Assignment operators
Increment/Decrement
Comparison operators
Logical operators
Bitwise operators
X = Y, Now both
= Equal sign Copy value from right to left.
X and Y have 5
(X / Y) will return
Return the Quetiont from
2(both are int, int
/ Division left operand by right
doesn't support
operand.
decimal)
Relational Operators
Relational operators are used for checking conditions whether the given
condition is true or false. If the condition is true, it will return non-zero value,
if the condition is false, it will return 0.
Oper
Name Description Example
ator
Logical Operators
Logical operators are used in situation when we have more then one
condition in a single if statement.
Conditional
Syntax :
Example :
void main()
int X=5,Y=2,lrg;
lrg = (X>Y) ? X : Y;
Output :
Largest number is : 5
Binary operator
Binary operators are those operators that works with at least two operands
such as (Arithmetic operators) +, -, *, /, %.
Unary operators are those operators that works with singal operands such as
(Increment or Decrement operators) ++ and --.
Special Operators:
::- Scope resolution operator
>>-Insertion Operator
<<-Extraction Operator
::*- Pointer-to-member decelerator
->*- Pointer-to-member operator
Prepared by Dr.S.Hemalatha, Department of Commerce (Computer Application), KAHE
12/39
Tokens, Expression and Control Structure 2016 – 2019 Batch
Manipulator:
endl:
used instead of ”\n”.
Example:
cout<<“welcome to csc”<<endl;
setw:
used for neat alignment during display.
Syntax:
setw (int value)
Example:
cout<<setw(5);
Program:
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main()
{
int m1=50,m2=500,m3=5000;
clrscr();
cout<<setw(5)<<"m1:"<<setw(5)<<m1<<endl;
cout<<setw(5)<<"m2:"<<setw(5)<<m2<<endl;
cout<<setw(5)<<"m3:"<<setw(5)<<m3<<endl;
}
Output:
m1: 50
m2: 500
m3: 5000
Type Cast:
Convert the data type of a variable to some other data type variable
Syntax:
(type name) expression //c
type name (expression) //c++
Example:
float (i);
Decision making statements
if ..else, jump, goto, break, continue- switch case statements
Control Structure:
Sequence structure
Selection structure
Loop structure
Selection Structure:
if statement
if…else
Nested if
if… else ladder
switch statement
if Statement:
Syntax:
if(condition)
{
True Block;
}
Next Statement;
Example:
if(i>10)
cout<<”i greater than 10”;
if …else Statement
Syntax:
if(condition)
{
True Block;
}
else
{
False Block;
}
Next Statement;
Example:
if(i>10)
cout<<”i greater than 10”;
else
cout<<”i less than 10”;
Nested if Statement:
Syntax:
if(condition 1)
{
if(condition 2)
{
True block
}
else
{
False block condition 2;
}
}
else
{
False block condition 1;
}
Next Statement;
Example:
if(m1>40)
{
if(m2>40)
{
cout<<”pass”;
}
else
{
cout<<”Fail”;
}
}
else
{
cout<<”Fail”;
}
if… else ladder:
if-else ladder is used for checking multiple conditions, if the first condition will
not satisfy, compiler will jump to else block and check the next condition,
whether it is true or not and so on.
Syntax:
if(condition 1)
{
True block-1
}
else if(condition 2)
{
True block -2;
}
else
{
False block;
}
Next Statement;
Example:
if(a>b)
{
if(a>c)
{
cout<<”A is Greatest”;
}
else
{
cout<<”C is Greatest”;
}
}
else
if(b>c)
{
cout<<”B is Greatest”;
}
else
{
cout<<”C is Greatest”;
}
Switch Case:
Syntax:
switch(expression)
{
case exp1:
Statements
case exp2:
Statements
………………
………………
default:
Statements
}
Example
i=4;
switch(i)
{
case 1:
cout<<”one”;
case 2:
cout<<”two”;
case 3:
cout<<”three”;
default:
cout<<”Wrong Choice”;
}
Loop Structure
Entry control:
Entry control Structure checks the condition First and the Statement is
executed
while loop
for loop
Exit control:
Exit control Structure First the Statement is Executed and then
checks the condition
do… while
While Loop:
While loop is also called entry control loop because, in while loop, compiler will
1st check the condition, whether it is true or false, if condition is true then
execute the statements.
Syntax:
while(Condition)
{
Statement Block
}
Example:
while(i<5)
{
cout<<”Welcome”;
i++;
}
For Loop:
Syntax:
for(initialization ; condition checking ; Increment/Decrement)
{
Statement Block
}
Example:
for(i=1;i<5;i++)
{
cout<<”Welcome”;
}
Do..While
The do-while loop is also called exit control loop because, in do-while loop,
compiler will 1st execute the statements, then check the condition, whether it
is true or false.
Syntax:
do
{
}while(condition);
Example:
do
{
cout<<”Welcome”;
i++;
}while(i<5);
It will never execute loop if It will executes loop at least once when the
condition is false. initial condition is false.
Break
Continue
GoTo
Break Statement
The break statement is used inside loop or switch statement. When compiler
finds the break statement inside a loop, compiler will abort the loop and
continue to execute statements followed by loop.
#include<iostream.h>
void main()
{
int a=1;
while(a<=10)
{
if(a==5)
break;
Output :
Statement 1
Statement 2
Statement 3
Statement 4
End of Program.
Continue Statement
The continue statement is also used inside loop. When compiler finds the
break statement inside a loop, compiler will skip all the followling statements
in the loop and resume the loop.
#include<iostream.h>
void main()
{
int a=0;
while(a<10)
{
a++;
if(a==5)
continue;
}
cout << "\nEnd of Program.";
}
Output :
Statement 1
Statement 2
Statemnet 3
Statement 4
Statement 6
Statement 7
Statement 8
Statement 9
Statement 10
End of Program.
Goto Statement
The goto statement is a jump statement which jumps from one point to
another point within a function.
goto label;
----------
----------
label:
----------
----------
#include<iostream.h>
void main()
{
cout << "\nStatement 1.";
cout << "\nStatement 2.";
cout << "\nStatement 3.";
goto last;
last:
Output :
Statement 1.
Statement 2.
Statement 3.
End of Program.
Function in C++
A function is a block of codes that performs a specific task and may return
value. The main() function is the first user defined function invoked by the
compiler. While it is possible to write any code within main function, it leads
number of problems. The program may become too large and complex and it is
difficult to test, debugg and maintain the complex code. For that reason, We
use function to place independent code in separate modules called function or
Function declaration
Function definition
Function call
Function declaration
Like variables, all the functions must be declared. Function declaration
statement includes function name, what function will take and what function
will return.
Syntax :
argument list : represents the type and number of value function will take,
values are sent by the calling statement.
Function definition
Function definition includes the actual working or implementation.
sum = x + y;
return sum;
}
var = function-name(val1,val2...n);
var can be any variable that will recieve value returning from function
definition.
int rs;
rs = Add(10,20); //calling statement
cout << "\nThe sum is : " << rs;
Call by Value
Call by Reference/Address
Call by Value
In this approach, the values are passed as function argument to the definition
of function.
#include<iostream.h>
void main()
{
int A=10,B=20;
fun(A,B); //Statement 1
Output :
Call by Reference
In this approach, the references/addresses are passed as function argument
to the definition of function.
#include<iostream.h>
void main()
{
int A=10,B=20;
fun(&A,&B); //Statement 1
Output :
The actual arguments can be variable The actual arguments can only be
or constant. variable.
The values of actual argument are The reference of actual argument are
sent to formal argument which are sent to formal argument which are
normal variables. pointer variables.
arguments. arguments.
Inline functions
When we make an inline function, compiler will replace all the calling
statements with the function definition at run-time.
Syntax:
inline function
{
function body
}
#include<iostream.h>
#include<conio.h>
inline int add(int a,int b)
{
return(a+b);
}
void main()
{
int m1,m2;
clrscr();
cout<<"Enter the first number:";
cin>>m1;
cout<<"Enter the Second number:";
cin>>m2;
cout<<"Addition Result:"<<add(m1,m2)<<endl;
}
Function overloading
More than one function with same name, with different signature in a class or
in a same scope is called function overloading. Signature of function includes:
Number of arguments
Type of arguments
Sequence of arguments
#include<iostream.h>
#include<conio.h>
class CalculateArea
public:
};
void main()
CalculateArea C;
C.Area(5); //Statement 1
C.Area(5,3); //Statement 2
C.Area(7,2.1f); //Statement 3
C.Area(4.7f,2); //Statement 4
Output :
Area of Rectangle is : 15
Example Program 2:
#include<iostream.h>
#include<conio.h>
int volume(int);
double volume(double,int);
long volume(long,int,int);
void main()
{
clrscr();
cout<<"Function with one argument:"<<volume(10)<<"\n";
cout<<"Function with two argument:"<<volume(5.6,10)<<endl;
cout<<"Function with three argument:"<<volume(56l,67,89)<<endl;
}
int volume(int s)
{
return(s*s*s);
}
double volume(double r,int h)
{
return(3.14*r*r*h);
}
long volume(long l,int b,int h)
{
return(l*b*h);
}
Unit – III
class class_name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
}
Example:
class book
{
int pgno;
public:
void getpage();
}
Creation of Objects:
Once the class is created, one or more objects can be created from the
class as objects are instance of the class.
int x;
Example:
exforsys e1;
Defining a Member
Definition in 2 places
Outside the class definition.
Inside the class definition.
Outside the Class Definition
Syntax:
----------
}
class_name:: A program may contain more than one class and these
classes may have similar member functions. Class_name:: tells the
compiler which class the function belongs to and the scope of the
member function is restricted to the class_name.
argument list Represents the type and number of value function will
take, values are sent by the calling statement.
#include<iostream.h>
#include<conio.h>
class Employee
{
int Id;
char Name[25];
int Age;
long Salary;
public:
void GetData();
void PutData();
};
void main()
{
Output :
Enter Employee Id : 1
Enter Employee Name : Kumar
Enter Employee Age : 29
Enter Employee Salary : 45000
Employee Id : 1
Employee Name : Kumar
Employee Age : 29
argument list Represents the type and number of value function will
take, values are sent by the calling statement.
#include<iostream.h>
#include<conio.h>
class Employee
{
int Id;
char Name[25];
int Age;
long Salary;
public:
void GetData() //Statement 1 : Defining GetData()
{
cout<<"\n\tEnter Employee Id : ";
cin>>Id;
};
void main()
{
Output :
Enter Employee Id : 1
Enter Employee Name : Kumar
Enter Employee Age : 29
Enter Employee Salary : 45000
Employee Id : 1
Employee Name : Kumar
Employee Age : 29
{
cout<<i<<"\n";
i--;
main();
}
}
Static member functions
#include<iostream.h>
class employee
{
char name[30];
float age;
public:
void get();
void put();
};
void employee::get()
{
cout<<"Enter name:";
cin>>name;
cout<<"Enter age:";
cin>>age;
}
void employee::put()
{
cout<<"Name:"<<name<<"\n";
cout<<"Age:"<<age<<"\n";
}
void main()
{
employee e[50];
int n;
cout<<"Enter the No of Employees:";
cin>>n;
cout<<"Enter the Details:";
for(int i=0;i<n;i++)
Prepared by Dr.S.Hemalatha, Department of Commerce (Computer Application) ,
KAHE
13/26
Classes and Objects 2016 – 2019 Batch
e[i].get();
cout<<"\nDetails of"<<n<<"Employees";
for(i=0;i<n;i++)
{
cout<<"\nEmployee"<<i+1<<"\n";
e[i].put();
}
}
Friendly functions
Private members are accessed only within the class they are declared.
Friend function is used to access the private and protected members of
different classes. It works as bridge between classes.
Syntax:
friend returntype functionname(Arg list)
Program:
#include<iostream.h>
class second;
class first
{
int a;
public:
void set(int x)
{
a=x;
}
friend void max(first,second);
};
class second
{
int b;
public :
void set(int y)
{
b=y;
}
friend void max(first,second);
};
void max(first m,second n)
{
if(m.a>=n.b)
cout<<m.a;
else
cout<<n.b;
}
void main()
{
first f;
f.set(10);
Prepared by Dr.S.Hemalatha, Department of Commerce (Computer Application) ,
KAHE
15/26
Classes and Objects 2016 – 2019 Batch
second s;
s.set(20);
max(f,s);
}
Constructors and destructors: Constructors
Constructors:
Characteristics
Should be in the public section
Invoked automatically
Do not have any return value
Cannot be inherited
Can have arguments
Cannot be virtual
Cannot refer to their address
Make implicit calls to the operators new and delete.
Types of Constructor
Default Constructor
Parameterize Constructor
Copy Constructoronstructor
#include<iostream.h>
#include<string.h>
class Student
{
int Roll;
char Name[25];
float Marks;
public:
void Display()
{
cout<<"\n\tRoll : "<<Roll;
cout<<"\n\tName : "<<Name;
cout<<"\n\tMarks : "<<Marks;
}
};
void main()
{
Output :
Roll : 1
Name : Kumar
Marks : 78.42
Default Constructor
Construct without parameter is called default constructor.
#include<iostream.h>
#include<string.h>
class Student
{
int Roll;
char Name[25];
float Marks;
public:
Student() //Default
Constructor
{
Roll = 1;
strcpy(Name,"Kumar");
Marks = 78.42;
}
void Display()
{
cout<<"\n\tRoll : "<<Roll;
cout<<"\n\tName : "<<Name;
cout<<"\n\tMarks : "<<Marks;
}
};
void main()
{
S.Display(); //Displaying
Student Details
Output :
Roll : 1
Name : Kumar
Marks : 78.42
Parameterized Constructors
Parameters are arguments to the Constructor
This can be done in 2 ways
By calling the Constructor explicitly
Class-name obj=constructorname(arg list);
By calling the Constructor implicitly
Class-name obj(arg list);
Program:
#include<iostream.h>
class assign
{
int a,b;
public:
assign(int x,int y)
{
a=x;
b=y;
}
void show()
{
cout<<"\nNumber1:"<<a;
cout<<"\nNumber2:"<<b;
}
};
void main()
{
assign f(34,35);
f.show();
assign s=assign(75,76);
s.show();
}
Copy Constructor
y=x.y;
}
void display()
{
cout<<"\nValues:"<<y;
}
};
void main()
{
copy a(111);
copy b(a);
copy c=a;
copy d; d=a;
cout<<"\nValue of a:";
a.display();
cout<<"\nValue of b:";
b.display();
cout<<"\nValue of c:";
c.display();
cout<<"\nValue of d:";
d.display();
}
#include<iostream.h>
class Method
{
public:
Method()
{
cout<<"\nNo Arguments";
}
Method(int i)
{
cout<<"\nInteger Argument:"<<i;
}
Method(double i)
{
cout<<"\nDouble Argument:"<<i;
}
Method(char i)
{
cout<<"\nCharacter Argument:"<<i;
}
};
void main()
{
Method b;
Method b1(5);
Method b2(6.5);
Method b3('c');
Prepared by Dr.S.Hemalatha, Department of Commerce (Computer Application) ,
KAHE
23/26
Classes and Objects 2016 – 2019 Batch
}
Dynamic Constructor
Basically, it's a way of constructing an object based on the run-time type
of some existing object. It basically uses standard virtual
functions/polymorphism.
class base
{
public:
virtual base* create() = 0;
virtual base* clone() = 0;
protected:
base();
base(const base&);
};
virtual der1 : public base
{
public:
base* create() { return new der1; }
base* clone() { return new der1(*this); }
};
virtual der2 : public base
{
public:
base* create() { return new der2; }
base* clone() { return new der2(*this); }
};
int main()
{
base* b = new der1;
Prepared by Dr.S.Hemalatha, Department of Commerce (Computer Application) ,
KAHE
24/26
Classes and Objects 2016 – 2019 Batch
base* b1 = b->create();
base* b2 = b->clone();
}
Destructor
int y;
public:
copy()
{
count++;
cout<<"\nNo Objects Created:"<<count;
}
~copy()
{ cout<<"\nNo Objects Deleted:"<<count;
count--;
}
};
void main()
{
copy a,b,c,d;
}
PART A (1 Mark)
(Online Examinations)
PART B ( 2 Marks)
1. Define Class.
2. Define Object.
3. How will you Specify a class
4. How will you define member functions
5. What is pointers to Members
6. Define Constructor
7. Define Destructor
8. How many types of Constructor
9. Define Static data members
10. What is Static Member Function
11. What is Nesting of Member Functions
12. What is Jump Students
13. What is Goto Statements
PART C (6 Marks)
1. Explain Member functions in a class
2. Explain Static Data members with example.
3. Explain Static Member functions with example
4. Describe Constructor and Destructor
5. Discuss Private Member Functions
6. Write a program to subtract two numbers (member functions
should be define outside the class)
7. Elucidate dynamic destructor with example.
8. Explain member function and nesting of member function
9. What is constructor? Explain the types of constructor with an
suitable example
10. Engrave on friend function with suitable example.
Unit – IV
{
cout<<"\nAddition of double:"<<a+b;
}
• Declaration:
RT operator operatorsymbol( argument list)
• Definition:
RT classname :: operator(op-arglist)
{
function body
}
Example:
void operator –()
• Operator function must be either member functions or friend
function
• Difference: a friend function will have only 1 argument for unary
operators and 2 arguments for binary operator
Steps:
• Create a class that defines the data type that is to be used in the
overloading operation
• Declare the operator function operator op() in the public part of the
class
• Define the operator function to implement the required operations
Example
#include<iostream.h>
class Add
{
int lat,log;
public:
Add(){}
Add(int l,int lt)
{
lat=l;
log=lt;
}
void show()
{
cout<<lat<<" ";
cout<<log<<" ";
}
Add operator -(Add o);
};
Add Add::operator -(Add o)
{
Add t;
t.lat=o.lat+lat;
t.log=o.log+log;
return t;
}
void main()
{
Add a(10,20),b(30,50);
a.show();
b.show();
a=a-b;
a.show();
}
y=-y;
z=-z;
}
void main()
{
space s;
s.getdata(10,-20,30);
cout<<"\nValues before Call Operator Overloading\n";
s.display();
-s;
cout<<"\nValues After Call Operator Overloading\n";
s.display();
}
Overloading binary operators
Time operator+(Time);
};
void Time::display(void)
{
cout<<h<<"hours and"<<m<<" Min\n";
}
Time Time::operator+(Time t)
{
Time t1;
t1.m=m+t.m;
int bal=t1.m/60;
t1.m=t1.m%60;
t1.h=h+t.h+bal;
return(t1);
}
void main()
{
Time h1,h2,h3;
h1=Time(2,50);
h2=Time(2,50);
h3=h1+h2;
cout<<"\nTime t1:";
h1.display();
cout<<"\nTime t2:";
h2.display();
cout<<"\nTime t3:";
h3.display();
}
type conversions
The constructor used for type conversion takes a single argument whose
type is to be converted. This conversion is done by overloaded = operator.
Conversion from class type to basic type
In this left hand operand of = operator is always a variable type or
basic type.
The constructor performs a fine job in conversion from basic to
class type.
The conversion of class to basic model is done by overloaded
casting operator.
The general form of an overloaded casting operator function is
operator typename()
{
………..
………..//function statement
}
Example:
String :: operator double()
{
double d=0;
d=s[0]+s[1];
return(d);
}
String is a class converted to basic type double, where s is a String class
object
String s1,s2;
float c1,c2;
c1=float(s1);
c2=s2;
Inheritance :- Inheritance
Advantage of Inheritance:
Reusability of code
Save a lot of time and efforts, retyping the same
Data and methods of super class are physically available to its
subclasses
Forms of Inheritance
In C++ there are 5 forms of inheritance.
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Defining derived classes
Example:
class ABC
{
…………..
…………..// base class members
}
class der : private ABC //Privately inherited from class ABC
{
…………..
…………..// derived class members
}
Base Class
Derived Class
Syntax:
Program:
#include<iostream.h>
class Rectangle
{
private:
float length ; // This can't be inherited
public:
float breadth ; // The data and member functions are inheritable
void Enter_lb(void)
{
cout << "\n Enter the length of the rectangle : ";
cin >> length ;
cout << "\n Enter the breadth of the rectangle : ";
cin >> breadth ;
}
float Enter_l(void)
{
return length ;
}
}; // End of the class definition
class Rectangle1 : public Rectangle
{
private:
float area ;
public:
void Rec_area(void)
{
area = Enter_l( ) * breadth ;
}
void Display(void)
{
cout << "\n Length = " << Enter_l( ) ;
cout << "\n Breadth = " << breadth ;
cout << "\n Area = " << area ;
}
};
void main(void)
{
Rectangle1 r1 ;
r1.Enter_lb( );
r1.Rec_area( );
r1.Display( );
}
Visibility of Inherited Members
Multilevel Inheritance:
C++ also provides the facility of multilevel inheritance, according to
which the derived class can also be derived by another class, which in
turn can further be inherited by another and so on.
Base Class
Derived Class 1
Derived Class 2
Syntax:
}
void DisplayData( )
{
Base::DisplayData();
cout << "\n d1 = " << d1;
}
};
class Derive2 : public Derive1
{
private:
int d2;
public:
void EnterData( )
{
Derive1::EnterData( );
cout << "\n Enter the value of d2: "; cin >> d2;
}
void DisplayData( )
{
Derive1::DisplayData( );
return 0;
}
Multiple Inheritance
When a class is inherited from more than one base class, it is known as
multiple inheritance.
Base Class 1 Base Class 2
Derived Class
Syntax:
void Enter_r(void)
{
cout << "\n\t Enter the radius: "; cin >> radius ;
}
void Display_ca(void)
{
cout << "\t The area = " << (22/7 * radius*radius) ;
}
};
class Rectangle // Second base class
{
protected:
float length, breadth ;
public:
void Enter_lb(void)
{
cout << "\t Enter the length : ";
cin >> length ;
cout <<"\t Enter the breadth : " ;
cin >> breadth ;
}
void Display_ar(void)
{
cout << "\t The area = " << (length * breadth);
}
};
class Cylinder : public Circle, public Rectangle // Derived class,
inherited
{ // from classes Circle & Rectangle
public:
void volume_cy(void)
{
cout << "\t The volume of the cylinder is: "<< (22/7*
radius*radius*length) ;
}
};
void main(void)
{
Circle c ;
cout << "\n Getting the radius of the circle\n" ;
c.Enter_r( );
c.Display_ca( );
Rectangle r ;
cout << "\n\n Getting the length and breadth of the rectangle\n\n";
r.Enter_lb( );
r.Display_ar( );
Cylinder cy ;
cout << "\n\n Getting the height and radius of the cylinder\n";
cy.Enter_r( );
cy.Enter_lb( );
cy.volume_cy( );
}
Hierarchical Inheritance:
When two or more classes are derived from a single base class,
then Inheritance is called the hierarchical inheritance.
In this type there exists a hierarchical relation in the inheritance.
Base Class
Prepared by Dr.S.Hemalatha, Department of Commerce (Computer Application),
KAHE
25/37
Derived Class 1 Derived Class 1 Derived Class 1
Operator Overloading and Inheritance 2016 – 2019 Batch
Syntax:
Example:
#include<iostream.h>
const int len = 20 ;
class student
{
private:
char F_name[len] , L_name[len] ;
int age,roll_no ;
public:
void Enter_data(void)
{
cout << "\n\t Enter the first name: " ; cin >> F_name ;
cout << "\t Enter the second name: "; cin >> L_name ;
cout << "\t Enter the age: " ; cin >> age ;
cout << "\t Enter the roll_no: " ; cin >> roll_no ;
}
void Display_data(void)
{
cout << "\n\t First Name = " << F_name ;
cout << "\n\t Last Name = " << L_name ;
cout << "\n\t Age = " << age ;
cout << "\n\t Roll Number = " << roll_no ;
}
};
class arts : public student
{
private:
char asub1[len] ;
char asub2[len] ;
char asub3[len] ;
public:
void Enter_data(void)
{
student :: Enter_data( );
cout << "\t Enter the subject1 of the arts student: ";
cin >> asub1 ;
cout << "\t Enter the subject2 of the arts student: ";
cin >> asub2 ;
cout << "\t Enter the subject3 of the arts student: ";
cin >> asub3 ;
}
void Display_data(void)
{
student :: Display_data( );
cout << "\n\t Subject1 of the arts student = " << asub1 ;
cout << "\n\t Subject2 of the arts student = " << asub2 ;
cout << "\n\t Subject3 of the arts student = " << asub3 ;
}
};
class science : public student
{
private:
char csub1[len], csub2[len], csub3[len] ;
public:
void Enter_data(void)
{
student :: Enter_data( );
cout << "\t Enter the subject1 of the science student: ";
cin >> csub1;
cout << "\t Enter the subject2 of the science student: ";
cin >> csub2 ;
cout << "\t Enter the subject3 of the science student: ";
cin >> csub3 ;
}
void Display_data(void)
{
student :: Display_data( );
cout << "\n\t Subject1 of the science student = " << csub1 ;
cout << "\n\t Subject2 of the science student = " << csub2 ;
cout << "\n\t Subject3 of the science student = " << csub3 ;
}
};
void main(void)
{
arts a ;
cout << "\n Entering details of the arts student\n" ;
a.Enter_data( );
cout << "\n Displaying the details of the arts student\n" ;
a.Display_data( );
science s ;
cout << "\n\n Entering details of the science student\n" ;
s.Enter_data( );
cout << "\n Displaying the details of the science student\n" ;
s.Display_data( );
}
Hybrid inheritance
Syntax:
}
class derived-class-name3 : visibility-mode derived-class-name1,
visibility-mode derived-class-name2
{
…………..
…………..// derived class members
}
Example:
#include<iostream.h>
#include<conio.h>
class stu
{
protected:
int rno;
public:
void get_no(int a)
{
rno=a;
}
void put_no(void)
{
cout<<"Roll no"<<rno<<"\n";
}
};
class test:public stu
{
protected:
float part1,part2;
public:
void display(void);
};
void result::display(void)
{
total=part1+part2+score;
put_no();
put_marks();
putscore();
cout<<"Total Score="<<total<<"\n";
}
int main()
{
clrscr();
result stu;
stu.get_no(111);
stu.get_mark(27.5,33.0);
stu.getscore(10.0);
stu.display();
return 0;
}
Virtual base classes
Grand Parents
Parent 1 Parent 2
Child
class base-class-name
{
…………..
…………..// base class members Grand Parents
}
class derived-class-name1 : virtual visibility-mode base-class-name
{
…………..
void put_no(void)
{
cout<<"Roll no"<<rno<<"\n";
}
};
class test:virtual public stu//Virtually inherited
{
protected:
float part1,part2;
public:
void get_mark(float x,float y)
{
part1=x;
part2=y;
}
void put_marks()
{
cout<<"Marks
obtained:\npart1="<<part1<<"\n"<<"part2="<<part2<<"\n";
}
};
class sports: public virtual stu
{
protected:
float score;
public:
void getscore(float s)
{
score=s;
}
void putscore(void)
{
cout<<"sports:"<<score<<"\n";
}
};
class result: public test, public sports
{
float total;
public:
void display(void);
};
void result::display(void)
{
total=part1+part2+score;
put_no();
put_marks();
putscore();
cout<<"Total Score="<<total<<"\n";
}
int main()
{
clrscr();
result stu;
stu.get_no(123);
stu.get_mark(27.5,33.0);
stu.getscore(6.0);
stu.display();
return 0;
Abstract classes
Unit – V
item *d=p;
int x,i;
float y;
for(i=0;i<3;i++)
{
cout<<"Input Code and Price for Item"<<i+1;
cin>>x>>y;
p->getdata(x,y);
p++;
}
for(i=0;i<3;i++)
{
cout<<"Item"<<i+1<<endl;
d->show();
d++;
}
}
this pointer
Syntax:
this - > variable or function name;
Prepared by Dr.S.Hemalatha, Department of Commerce (Computer Application),
KAHE 3/53
Pointers and File Concepts 2016 – 2019 Batch
Example:
this->a;
return this;
Program:
#include<iostream.h>
class person
{
char name[20];
float age;
public:
person(char *s, float a)
{
strcpy(name,s);
age=a;
}
person &person :: greater(person &x)
{
if(x.age>=age)
return x;
else
return *this;
}
void display()
{
cout<<"Name : "<<name;
cout<<"\nAge : "<<age;
}
};
void main()
{
person p1("Raja",42.78),p2("Ram",35.8),p3("Arun",45.3);
person p=p1.greater(p3);
cout<<"Elder Person is :\n ";
p.display();
p=p1.greater(p2);
cout<<"Elder Person is :\n ";
p.display();
}
Pointers are used not only to base class but also to derived class.
Pointers to objects of a base class are type-compatible with
pointers to objects of derived class.
A single pointer variable can be made to point to object belonging
to different classes.
Example:
B *ptr;
B b;
D d;
ptr=&b;
Program:
#include<iostream.h>
class BC
{
public :
int b;
void show()
{
Prepared by Dr.S.Hemalatha, Department of Commerce (Computer Application),
KAHE 5/53
Pointers and File Concepts 2016 – 2019 Batch
cout<<"b = "<<b<<endl;
}
};
class DC: public BC
{
public:
int d;
void show()
{
cout<<"b = "<<b<<endl;
cout<<"d = "<<d<<endl;
}
};
void main()
{
BC *ptr;
BC base;
cout<<"Base Class Pointer Call"<<endl;
ptr=&base;
ptr->b=100;
ptr->show();
cout<<"Base Class Pointer Call using Derived Class"<<endl;
DC dc;
ptr=&dc;
ptr->b=200;
ptr->show();
cout<<"Derived Class Pointer Call"<<endl;
DC *dptr;
dptr=&dc;
dptr->d=100;
dptr->show();
cout<<"Using (DC*)bptr)\n";
((DC *)ptr)->d=200;
((DC *)ptr)->show();
}
Virtual functions
Program:
#include<iostream.h>
class Base
{
public :
void display()
{
cout<<"\nDisplay Base Class";
}
virtual void show()
{
cout<<"Base Class Show";
}
};
class Derived: public Base
{
public :
void display()
{
cout<<"\nDisplay Derived Class";
}
virtual void show()
{
cout<<"Derived Class Show";
}
};
void main()
{
Base *ptr;
Base b;
Derived d;
cout<<"\nPointer point to Base Class";
ptr=&b;
ptr->display();
ptr->show();
cout<<"\nPointer point to Derived Class";
ptr=&d;
ptr->display();
ptr->show();
}
Rules:
1. The virtual function must be members of some class.
2. They can not be static members.
3. They are accessed by using object pointers.
4. A virtual function can be a friend of another class.
5. A virtual function in a base class must be defined, even through it
may not be used.
6. The prototype of the base class version of a virtual function and all
the derived class versions must be identical. If two functions with
the same name have different prototypes, C++ considers them as
overloaded function.
7. Can have virtual constructors not have virtual destructors.
8. While a base class pointer can point to any type of derived object,
the reverse is not true.
9. When a base class pointer points to a derived class, incrementing
or decrementing it will not make it to point to the next object of the
derived class
C++ Streams:
The I/O system in C++ is designed to work with a wide variety of
devices including terminals, disks, and tape drives.
The I/O stream supplies an interface to the programmer that
independent of the actual device being accessed. This interface is known
as stream.
A stream is a sequence of bytes.
It acts either as a source from which the input data can be
obtained or as a designation to which data can be sent.
The source stream that provides data to the program is called the
input stream and the designation stream that receives output from the
program is called the output stream.
Input Stream
Input Device
Program
Output Device
Output Stream
The data in the input stream can come from the keyboard or any
other storage devices.
The data in the output stream can go to the screen or any other
storage devices.
A stream is an interface between the program and the I/O devices.
C++ contains pre-defined streams that are automatically opened
when a program begins its execution.
cin and cout also belongs to such streams.
cin represents the input stream connected to the standard input
device.
cout represents the output stream connected to the standard
output device.
C++ stream classes
The C++ I/O system contains a hierarchy of classes that are used
to define various streams to deal with console and disk files. These
classes are called stream classes.
Prepared by Dr.S.Hemalatha, Department of Commerce (Computer Application),
KAHE 11/53
Pointers and File Concepts 2016 – 2019 Batch
ios
iostream
The objects cin and cout for the input and output of data of
various types.
This is done by overloading the operator >> and <<.
The operator >> is overloaded in the istream class and <<
overloaded in the ostream.
Example:
cin>>a;
cout<<a;
put() and get() Functions:
The classes istream and ostream defines two member functions
get() and put() to handle the single character input/output operations.
There are two type of get() function
get(char *) – assign the input to a variable
get(void) – returns the input character.
Example:
cin.get(c); //read and assign the value for c
c=cin.get(); // returns the read character to c
put() is a member of ostream class, can be used to output a line of
text, character by character.
Syntax:
cin.put(char *);
Example:
cout.put(‘m’);
Program:
#include<iostream.h>
void main()
{
char c;
int ct=0;
cout<<"Input Text:\n";
cin.get(c);
cout.put(c);
while(c!='\n')
{
cout.put(c);
c=cin.get();
ct++;
}
cout<<"Number of Characters Entered : "<<ct;
}
getline() and write() Function:
getline() and write() is used to read the text line by line.
The getline() function reads a whole line of text that ends with a
newline character.
Syntax:
cin.getline(line,size)
line- variable name
The reading is terminated as soon as either the newline character
‘\n’ is encountered or size-1 characters are read.
Example:
char name[20];
cin.getline(name,20);
Program:
#include<iostream.h>
void main()
{
char name[25];
cout<<"\nEnter the name:\n";
cin.getline(name,20);
cout<<"\nName : "<<name;
}
The write() function display an entire line
Syntax:
cout.write(line,size)
line- variable name
The writing is terminated as soon as either the newline character
‘\n’ is encountered or size-1 characters are written.
Example:
char name[20]=”welcome”;
cout.write(name,20);
Program:
#include<iostream.h>
#include<string.h>
void main()
{
char name[25];
int i;
cout<<"\nEnter the name:\n";
cin.getline(name,20);
int l1=strlen(name);
for(i=1;i<l1;i++)
{
cout.write(name,i);
cout<<endl;
}
for(i=l1;i>0;i--)
{
cout.write(name,i);
cout<<endl;
}
}
width():
cout.width(2);
cout<<sum<<"\n";
}
Output:
Items Cost Total Values
7 75 525
12 100 1200
80 125 10000
89 90 8010
Grand Total=19735
precision():
To specify the number of digits to be displayed after the decimal
point of a float values.
Syntax:
cout.precision(size)
Example:
cout.precision(2);
Program:
#include<iostream.h>
#include<math.h>
void main()
{
cout.precision(3);
cout.width(7);
cout<<"Values";
cout.width(15);
cout<<"Squrt values\n";
for(int i=1;i<5;i++)
{
cout.width(5); cout<<i; cout.width(13);
cout<<sqrt(i)<<endl;
}
}
Output:
Values Squrt values
1 1
2 1.414
3 1.732
4 2
fill():
To specify a character that is used to fill the unused portion of a
field
Syntax:
cout.fill(character)
Example:
cout.fill(‘*’);
Program:
#include<iostream.h>
void main()
{
int a=5679; cout.width(10);
cout.fill('*'); cout<<"Values"; cout<<a<<"\n";
}
Output:
****Values5679
setf():
To specify format flags that can control the form of output display.
Syntax:
cout.setf(arg1,arg2);
arg1-formatting flags defined in the class ios.
arg2-formatting flags defined in the class ios. It is also known as
bit fields
Flags and Bit Fields
Format required Flag (arg1) Bit-field(arg2)
Left-justified O/P ios::left ios::adjustfield
Right- justified O/P ios::right ios::adjustfield
Padding after sign or
ios::internal ios::adjustfield
base Indicator(+##20)
Scientific notation ios::scientific ios::floatfield
Fixed point notation ios::fixed ios::floatfield
Decimal base ios::dec ios::basefield
Octal base ios::oct ios::basefield
Hexadecimal base ios::hex ios::basefield
insertion
Example:
cout.setf(ios::left. ios::adjustfield);
Program:
#include<iostream.h>
#include<math.h>
void main()
{
cout.fill('*');
cout.setf(ios::left,ios::adjustfield);
cout.width(10); cout<<"Values";
cout.setf(ios::right,ios::adjustfield);
cout.width(15);
cout<<"Sqrt Of Value \n";
cout.fill('.'); cout.precision(4);
cout.setf(ios::showpoint); cout.setf(ios::showpos);
cout.setf(ios::fixed,ios::floatfield);
for(int n=1;n<10;n++)
{
cout.setf(ios::internal,ios::adjustfield);
cout.width(5); cout<<n;
cout.setf(ios::right,ios::adjustfield);
cout.width(20);
cout<<sqrt(n)<<endl;
}
cout.setf(ios::scientific,ios::floatfield);
cout<<"sqrt(100)= "<<sqrt(100)<<"\n";
}
Output:
Values****Sqrt Of Value
+...1.............+1.0000
+...2.............+1.4142
+...3.............+1.7321
+...4.............+2.0000
+...5.............+2.2361
+...6.............+2.4495
+...7.............+2.6458
+...8.............+2.8284
+...9.............+3.0000
sqrt(100)= +1.0000e+01
Program:
#include<iostream.h>
#include<iomanip.h>
void main()
{
cout.setf(ios::showpoint);
cout<<setw(5)<<"n"<<setw(15)<<"Inverse of n"<<setw(15)<<"Sum of
terms"<<endl<<endl;
double term, sum;
for(int n=1;n<10;n++)
{
term=1.0/float(n);
sum=sum+term;
cout<<setw(5)<<n<<setw(14)<<setprecision(2)<<setiosflags(ios::scientific)<
<term<<setw(13)<<resetiosflags(ios::scientific)<<sum<<endl;
}
}
Output:
n Inverse of n Sum of terms
1 1.00e+00 1.00
2 5.00e-01 1.50
3 3.33e-01 1.83
4 2.50e-01 2.08
5 2.00e-01 2.28
6 1.67e-01 2.45
7 1.43e-01 2.59
8 1.25e-01 2.72
9 1.11e-01 2.83
Output:Height :
56 inches
Input Stream
Input Device
Output Device
The C++ I/O system contains a set of classes that define the file
handling methods.
File handling class includes ifstream, ofstream, and fstream. These
classes are derived from the corresponding iostream class.
These are the class designed to manage the disk files
All the classes are declared in fstream so all the program should
include this header file
ios
iostream
filebuf
iostream
fstream base file
File Operations:
Open file
Read and Write Operations
Closing a file
outf.close();
ifstream inf("Item");
inf>>name;
inf>>cost;
cout<<"\n Item Name:"<<name<<"\n";
cout<<"Item cost:"<<cost<<"\n";
inf.close();
}
Opening a Files Using open():
The function open() can be used to open multiple files that use
the same stream object.
Syntax:
File-stream-class stream-object;
stream-object.open(“file name”);
Example:
ofstream outfile;
outfile.open(“data”);
………………..
………………..
outfile.close();
Program:
#include<iostream.h>
#include<fstream.h>
void main()
{
ofstream outf;
char name[30];
int i;
outf.open("prog");
cout<<name<<"\n";
}
inf.close();
}
Detecting End of File:
eof() function is used to detect end of File.
It is the member function of ios class.
It returns a non-zero value if the end-of-file condition is
encountered and a zero otherwise.
Example:
if(fileobj.eof() !=0)
{ exit(0);}
File Modes:
istream and ostream constructors and function open() to create
new files as well as to open the existing files.
open() method takes two arguments one for file name and other for
mode.
Syntax:
Stream-object.open(“file-name”,mode);
mode specifies the purpose for which the file is opened.
The default mode values are:
ios::in for ifstream functions meaning open for reading only.
ios::out for ofstream functions meaning open for writing only.
File Mode Parameters:
Parameter Meaning
ios::app Append to end of file
ios::ate Go to end of the file on opening
ios::binary Binary file
ios::in Open file for reading only
All I/O streams objects have, at least, one internal stream pointer:
ifstream, like istream, has a pointer known as the get pointer that points
to the element to be read in the next input operation.
ofstream, like ostream, has a pointer known as the put pointer that
points to the location where the next element has to be written.
Finally, fstream, inherits both, the get and the put pointers, from
iostream (which is itself derived from both istream and ostream).
File Manipulators
seekg(offset, refposition );
seekp(offset, refposition );
The parameter offset represents the number of bytes the file pointer is to
be moved from the location specified by the parameter refposition.
The refposition takes one of the following three constants defined in the
ios class.
file.close();
}
write() and read() function:
The function write() and read() handles the data in binary
form. This means that the values stored in the disk file in the same
format in which they stored in the internal memory.
An int takes two bytes to store its value in the binary form,
irrespective of its size.
The binary format is more accurate for storing the numbers
in the exact internal representation.
The binary format is much faster to saving the data to.
Syntax:
inFile-object.read((char *) &v, sizeof(v))
outFile-object.write((char *) &v, sizeof(v))
The first argument is the address of variable v.
The second argument is the length of the variable in bytes.
The address of the variable must be cast to type char *.
Program:
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
void main()
{
float height[5]={176,182,167.89,177.9,160.24};
ofstream ofile;
int i;
ofile.open("data");
ofile.write((char *) &height, sizeof(height));
ofile.close();
ifstream infile;
infile.open("data");
infile.read((char *) &height, sizeof(height));
for(i=0;i<5;i++)
{
cout.setf(ios::showpoint);
cout<<setw(10)<<setprecision(2)<<height[i]<<endl;
}
infile.close();
}
Reading and Writing a Class Object:
C++ supports features for writing to and reading from the disk files
objects directly.
The binary input and output functions read() and write() are
designed to do exactly this job.
These functions handle the entire structure of an object as a single
unit, using the computer’s internal representation of data.
For instance, the function write() copies a class object from the
memory byte by byte with no conversion.
Only data members are written to the disk file and the member
functions are not.
The length of the object is obtained by sizeof operator.
Program:
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
class Inventory
{
char name[20];
int code;
float cost;
public:
void readdata();
void show();
};
void Inventory::readdata()
{
cout<<"Enter Name: ";
cin>>name;
cout<<"Enter Code: ";
cin>>code;
cout<<"Enter Cost: ";
cin>>cost;
}
void Inventory::show()
{
cout<<setiosflags(ios::left)<<setw(10)<<name
<<setiosflags(ios::right)<<setw(10)<<code
<<setprecision(2)<<setw(10)<<cost<<endl;
}
void main()
{
Inventory item[3];
fstream file;
file.open("stock.dat",ios::in |ios::out);
cout<<"Enter Details of Items\n";
for(int i=0;i<3;i++)
{
item[i].readdata();
file.write((char *) &item[i], sizeof(item[i]));
}
file.seekg(0);
cout<<"\n\nOutput\n\n";
for(i=0;i<3;i++)
{
file.read((char *) &item[i], sizeof(item[i]));
item[i].show();
}
file.close();
}
public:
void readdata();
void show();
};
void Inventory::readdata()
{
cout<<"Enter Name: ";
cin>>name;
cout<<"Enter Code: ";
cin>>code;
cout<<"Enter Cost: ";
cin>>cost;
}
void Inventory::show()
{
cout<<setiosflags(ios::left)<<setw(10)<<name
<<setiosflags(ios::right)<<setw(10)<<code
<<setprecision(2)<<setw(10)<<cost<<endl;
}
void main()
{
Inventory item;
fstream file;
file.open("stock.dat",ios::ate| ios::in |ios::out |ios::binary);
file.seekg(0,ios::beg);
cout<<"\nCurrent Contant of File\n";
while(file.read((char *) &item, sizeof(item)))
{
item.show();
}
file.clear();
cout<<"\nAdd An Item\n";
item.readdata();
char ch;
cin.get(ch);
file.write((char *) &item, sizeof(item));
file.seekg(0);
cout<<"\nContant of File After Appended\n";
while(file.read((char *) &item, sizeof(item)))
{
item.show();
}
int ls=file.tellg();
int n=ls/sizeof(item);
cout<<"\nNumber of Objects="<<n;
cout<<"\nTotal bytes in the file="<<ls;
cout<<"Modify An Item";
int no;
cout<<"\nEnter the Object Number to Update : ";
cin>>no;
cin.get(ch);
int loc=(no-1)*sizeof(item);
if(file.eof())
file.clear();
file.seekp(loc);
cout<<"\nEnter New values of object:\n";
item.readdata();
cin.get(ch);
The first argument is always the file name and contains the
program to be executed.
The value of argc would be 3 and the argv would be an array of 3
pointers to strings
argv[0] program-file-name
argv[1] first-file-name //used for reading purpose
argv[2] second-file-name //used for writing purpose
Templates:
Templates is one of the features added to C++ recently.
It is a new concept which enables us to define generic classes and
functions and thus provides support for generic programming.
Generic programming is an approach where generic types are used
as parameters in algorithms so that they work for a variety of suitable
data types and data structure.
A template can be used to create a family of classes or functions.
For example, a class template for an array class would enable us to
create arrays of various data types such as int array and float array.
Similarly, define a template for a function, say mul(), that would
help us create various versions of mul() for multiplying int, float and
double type values.
A template can be considered as a kind of macro.
When an object of a specific type is defined for actual use, the
template definition for that class is substitute with required data type.
Since a template defined with a parameter that would be replaced by a
specified data type at the time of actual use of the class or function, the
templates are sometimes called parameterized classes or functions.
Class templates
Class Templates:
A simple process to create a generic class using a template with
anonymous type.
template is the keyword used to create Template
The class template definition is very similar to an ordinary class
definition expect the prefix template<class T> and the use of type T.
This prefix tells the compiler that is going to declare a template
and use T as a type name in the declaration.
Syntax:
template <class T>
class class-name
{
//……
//class member specification
//with anonymous type T
//wherever appropriate
//……..
};
Example:
int size=3;
template<class T>
class vector
{
T* v;
int size;
public:
vector()
{
v=new T[size];
for(int i=0;i<3;i++)
v[i]=0;
}
vector(T* a)
{
for(int i=0;i<size;i++)
v[i]=a[i];
}
T operator *(vector &y)
{
T sum=0;
for(int i=0;i<size;i++)
sum+=this->v[i]*y.v[i];
return sum;
}
};
Class Templates with Multiple Parameters:
More than one generic data type in a class template.
It is declared as a comma separated list within the template
specification .
Syntax:
template <class T1, class T2,…,class Tn>
class class-name
{
……
……
……//body of the class
};
Program:
#include<iostream.h>
template<class T1, class T2>
class Test
{
T1 a;
T2 b;
public:
Test(T1 x, T2 y)
{
a=x;
b=y;
}
void show()
{
cout<<"\na : "<<a<<"\nb : "<<b;
}
};
void main()
{
Test <float, int> t1(1.23,123);
Test <int, char> t2(100,'M');
t1.show();
t2.show();
}
Function templates
Syntax:
template <class T>
return-type function-name(argument of type T)
{
//……
//body of function
//with type T
//wherever appropriate
//……..
}
The function template syntax is similar to that of the class
template expect that defining functions instead of classes.
Use template parameter T as and when necessary in the function
body and its argument list.
Program:
#include<iostream.h>
template<class T>
void swap(T &x, T &y)
{
T temp=x;
x=y;
y=temp;
}
void fun(int m,int n,float a,float b)
{
cout<<"\nm and n before swap: "<<m<<" "<<n;
swap(m,n);
cout<<"\nm and n after swap: "<<m<<" "<<n;
cout<<"\na and b before swap: "<<a<<" "<<b;
swap(a,b);
cout<<"\na and b after swap: "<<a<<" "<<b;
}
void main()
{
fun(100,200,11.53,33.44);
}
Function Templates with Multiple Parameters:
Use more than one generic data type in the template statement
using a comma-separated list.
Syntax:
template <class T1, class T2,…,class Tn>
return-type function-name(arguments of types T1,T2,….)
{
……
……
……//body of the function
}
Program:
void main()
{
display(11.53);
display(44);
display("welcome");
}
v[i]=a[i];
}
template<class T>
vector<T>::operator *(vector &y)
{
T sum=0;
for(int i=0;i<size;i++)
sum+=this->v[i]*y.v[i];
return sum;
}
Exception handling
try {
// code that could throw an exception
}
[ catch (exception-declaration) {
// code that executes when exception-declaration is thrown
// in the try block
}
[catch (exception-declaration) {
// code that handles another exception type
}]...]
// The following syntax shows a throw expression:
throw [expression]
Prime Number
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
int st_no,end_no,div,no_div=0;
cout<<"Enter the starting no ";
cin>>st_no ;
cout<<"Enter the enging no ";
cin>>end_no ;
while(st_no<=end_no)
{ div=st_no;
no_div=0;
while(div>=1)
{
if(st_no%div==0)
{
no_div= no_div+ 1 ;
}
div--;
}
if(no_div<=2)
{
cout<<st_no<< " IS PRIME"<<endl<<endl;
}
st_no++;
}
return 0;
}
String Program
#include <iostream>
#include <string>
#include <fstream>
#include <conio.h>
using namespace std;
int main()
{
ifstream file;
string s, city, bigstring, substring;
int count = 0;
file.open("c:\\cities.txt");
cout << "Enter all or part of a city name: ";
getline(cin,city);
if (bigstring.find(substring) != -1)
while (getline(file,s))
{
cout << s << endl;
count++
}
cout << "There were " << count << " matches in the file" << endl;
getch();
return 0;
}
Palindrome
#include <iostream>
#include <deque>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string input;
deque<string> stackOne;
deque<string> stackTwo;
cout << "Enter a text . Do not include spaces or punctuation.\n";
getline(cin, input);
stackOne.push_front(input);
while(!stackOne.empty())
{
input = stackOne.front();//retrieve the user entered input
stackTwo.push_front(input); // put input into stack two at
the front
}
if(stackOne == stackTwo)
{
cout << "It is a palindrome." << endl;
}
else
cout << "It is not a palindrome." << endl;
return 0;
}
PART A (1 Mark)
(Online Examinations)
PART B (2 Marks)
PART C ( 6 Marks)
1. Describe on file operations.
2. Explain Virtual Functions with example.
3. Describe about Pointers to Object
4. Describe about Pointers to Derived Classes.
5. Explain file stream Operations.
6. Explain file pointers and their manipulators.
7. List out and explain Sequential I/O operations.
8. Write a program using file operation (to open and close a file).
9. Describe file pointers with example.
10. Differentiate between pointers to object and pointers to derived class.