Object Oriented Programming Using C++: Auccs11
Object Oriented Programming Using C++: Auccs11
Prof. K.ARUNA
Prof. A.AJITHA
1
OBJECT ORIENTED
S1
PROGRAMMING USING C++
CC
Department of Computer Science
AU
Unit - I
1. Define OOP?
Object-oriented programming can b seen as an extension o procedural programming in wich
programs are made up o collection of individual units called objects that have a distnts purpose and
function with limited or no dependencies on implementation.
3. what is a keyword?
The keywords carry a special meaning for the C++ compiler.
1
Ex: auto, break, case, char, etc.,
4. What is identifier?
An identifier is the name given by user for a unit of program like variables, constant functions.
5. Write the rule for framing identifiers?
I.
II.
III.
IV.
V.
S1
Combination of letters and digits
First character should be a letter
No special character is allowed except underscore
Upper and lower case letters are significant.
No keyword should be used as an identifier.
6. What is data type?
Data type identifies the type of data and associated operations for handling it.
CC
Ex: int, float, char
7. What are the various data types?
There are various data types, which are given below.
I. Fundamental data type – int, float, char, double, void
II. Derived data type – array, pointer functions, reference
III. User-defined data type – class, structure, union, enumeration
8. Define variable.Give some example?
An identifier which can change its value during the execution of program is called as variable.
AU
Variable plays a vital role in programming as all manipulations are carried out here.
Example: int a ;
9. What is an expression?
An expression is the statement of combination of operators and related operands.
Example: A+B*(C/D)
10. Define manipulator.
Manipulators are set of functions used to manipulate output formats. They provide the same
features as that of ios members but manipulators are convenient to use than ios. Iomanip is the header file
for manipulators.
1. Explain inline function. Also write a C++ program – to find biggest of two numbers using inline
function.
The inline keyword suggests that the compiler substitute the code within the function definition
in place of each call to that function. This function takes less time to execute. An inline function is a
function that is explained in a line.
1
The function is not recursive
Syntax:
inline return_type function_name(parameter list)
{
Example:
}
statements;
}
return a+b; S1
CC
Program :
#include<iostream>
using namespace std;
inline int max(int x, int y)
{
if (x>y)
return x;
AU
else
return y;
}
int main()
{
int a, b;
cout<<"Enter the first number: ";
cin>>a;
cout<<"Enter the second number: ";
cin>>b;
cout<<"The maximum number is "<<max(a,b);
}
3
1. Introduction to iostream: C++ uses the iostream library for input and output operations. The
main components are cin for input and cout for output. Formatted I/O in C++ involves
controlling how data is read from and written to these streams.
2. Manipulators: C++ provides several stream manipulators to control the formatting of data:
std::setw(n): Sets the width of the field used for output. For example, std::cout <<
std::setw(10) << 42; prints 42 with a total width of 10 characters, padding with spaces if
necessary.
std::setprecision(n): Sets the number of decimal places for floating-point numbers. For
instance, std::cout << std::fixed << std::setprecision(2) << 3.14159; prints 3.14.
1
std::left, std::right, and std::internal: Align output within the field. std::left aligns text
to the left, std::right to the right, and std::internal aligns numbers in a way that maintains
their placement.
3. Format Specifiers and Flags: Unlike C's printf, C++'s iostream uses manipulators rather than
S1
format specifiers. However, the manipulators offer similar functionality:
Width and Precision: Control the width and precision of numeric output.
Fill Characters: std::setfill(c) sets the fill character for padding
4. Input Formatting: Input formatting is handled by cin with manipulators like std::ws (to ignore
leading whitespace) and custom extraction operators for more complex types. For example,
CC
extracting data using cin >> variable will handle whitespace and formatting based on the data
type
3. What is function overloading? Write a C++ program to explain function overloading.
Definition:
Function overloading is a feature in C++ that allows multiple functions to have the same
name but different parameter lists. The compiler distinguishes between these functions based on
the number and type of arguments passed. This is useful for performing similar operations with
AU
different types or numbers of inputs, thereby enhancing code readability and reusability.
Key Points:
1. Function Signature: The function signature includes the function name and the
parameter list (number, type, and order of parameters). It does not include the return type.
2. Return Type: Overloading does not consider the return type; thus, two functions with
the same name and parameter list but different return types are not considered overloaded.
Program:
#include <iostream>
using namespace std;
int main()
{
1
int intValue = 5;
float floatValue = 4.5;
int int1 = 3, int2 = 6;
S1
// Call the overloaded functions
cout << "Square of integer " << intValue << " is: " << square(intValue) << endl;
cout << "Square of float " << floatValue << " is: " << square(floatValue) << endl;
cout << "Product of integers " << int1 << " and " << int2 << " is: "
<< square(int1, int2) << endl;
CC
return 0;
}
1. Function Declarations:
- int square(int x)`: Computes the square of an integer.
- float square(float x)`: Computes the square of a floating-point number.
AU
- int square(int x, int y)`: Computes the product of two integers (demonstrates multiple
parameters).
2. Function Definitions:
- Each `square` function has a different parameter list:
- One takes a single integer.
- One takes a single float.
- One takes two integers.
3. Function Calls:
- In `main()`, the `square` function is called with different argument types and numbers,
demonstrating how the compiler resolves which version of the function to invoke based on the
arguments.
Output:
5
Square of integer 5 is: 25
Square of float 4.5 is: 20.25
Product of integers 3 and 6 is: 18
In this example, function overloading allows the use of the same function name `square`
to handle different types and numbers of parameters, demonstrating its utility in creating clean
and intuitive code.
1
S1
CC
1. Preprocessor Directives
Preprocessor directives are commands that are processed before the actual compilation of
the program begins. They are used to include header files, define constants, and perform other
preprocessing tasks.
2. Namespace
AU
Namespaces are used to group identifiers (like functions, variables, etc.) and to prevent
name conflicts. The std namespace is commonly used for standard library features.
3. Main Function
The main function is the entry point of a C++ program. It is where the execution of the
program starts. Every C++ program must have a main function.
4. Variable Declarations and Definitions
Variables are used to store data that can be manipulated throughout the program. They
must be declared before they are used.
5. Function Definitions
Functions are reusable blocks of code designed to perform specific tasks. Functions can
be defined and then called from the main function or other functions.
6. Statements and Expressions
Statements are instructions that the program executes, while expressions are
combinations of variables, constants, and operators that produce a value.
6
7. Comments
Comments are used to explain and annotate the code, making it easier to understand and
maintain. They are ignored by the compiler.
1
2 beginning. The loop will only of whether the condition is true
run if the condition evaluates to or false initially. The condition
true. is checked after the execution of
the code block.
7
1. Encapsulation
Encapsulation is the concept of bundling the data (attributes) and methods (functions) that operate on the data
into a single unit or class. It also involves restricting access to some of the object's components, which helps in
preventing unintended interference and misuse.
2. Inheritance
Inheritance is a mechanism where one class (derived or child class) inherits attributes and methods from
another class (base or parent class). This promotes code reuse and establishes a hierarchical relationship
between classes.
3. Polymorphism
Polymorphism means "many forms" and allows objects of different classes to be treated as objects of a
1
common base class. It enables a single function or operator to operate differently based on the object type.
4. Abstraction
5. Class
S1
Abstraction involves hiding complex implementation details and showing only the essential features of an
object. This simplifies interaction with the object by exposing only relevant attributes and methods.
The building block of C++ that leads to Object-Oriented programming is a Class. It is a user-defined data
type, which holds its own data members and member functions, which can be accessed and used by
creating an instance of that class.
CC
6. Object
An Object is an identifiable entity with some characteristics and behavior. An Object is an instance of a
Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is
created) memory is allocated.
AU
1. Arithmetic Expressions
8
Definition: Arithmetic expressions involve arithmetic operators that perform mathematical operations such as
addition, subtraction, multiplication, and division.
Operators:
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
% (Modulus)
Example:
int a = 10;
int b = 5;
int sum = a + b; // Arithmetic addition
1
int product = a * b; // Arithmetic multiplication
int remainder = a % b; // Modulus operation
2. Relational Expressions
Operators:
== (Equal to)
S1
Definition: Relational expressions compare two values and evaluate to a boolean result (true or false). They are
used to form conditions for control flow statements.
CC
!= (Not equal to)
< (Less than)
> (Greater than)
<= (Less than or equal to)
>= (Greater than or equal to)
Example:
int x = 10;
AU
int y = 20;
bool isEqual = (x == y); // Checks if x is equal to y
bool isLess = (x < y); // Checks if x is less than y
3. Logical Expressions
Definition: Logical expressions combine boolean values using logical operators to form complex conditions.
They are used in decision-making and looping constructs.
Operators:
9
Example:
bool a = true;
bool b = false;
bool result1 = a && b; // Logical AND: false
bool result2 = a || b; // Logical OR: true
bool result3 = !a; // Logical NOT: false
4. Bitwise Expressions
Definition: Bitwise expressions perform bit-level operations on integer data types. They operate on the binary
representations of numbers.
Operators:
1
| (Bitwise OR)
^ (Bitwise XOR)
~ (Bitwise NOT)
<< (Left shift)
>> (Right shift)
Example:
5. Assignment Expressions
Definition: Assignment expressions assign a value to a variable. They can be simple or combined with
arithmetic operations.
Operators:
AU
= (Simple assignment)
+= (Addition assignment)
-= (Subtraction assignment)
*= (Multiplication assignment)
/= (Division assignment)
%= (Modulus assignment)
Example:
int a = 10;
Definition: Increment and decrement expressions increase or decrease the value of a variable by one. They can
be used in both prefix and postfix forms.
Operators:
++ (Increment)
-- (Decrement)
Example:
int a = 5;
1
int b = ++a; // Prefix increment: a is incremented to 6, then b is assigned 6
int c = a--; // Postfix decrement: c is assigned 6, then a is decremented to 5
S1
Definition: The conditional expression, also known as the ternary operator, is a shorthand for the if-else
statement. It evaluates a condition and returns one of two values based on the result.
Operator:
CC
? : (Ternary operator)
Example:
int a = 10;
int b = (a > 5) ? 100 : 200; // If a is greater than 5, b is assigned 100; otherwise, 200
AU
8. Comma Expression
Definition: Comma expressions evaluate multiple expressions in sequence and return the result of the last
expression. They are often used in for loops or when multiple expressions need to be executed in a single
statement.
Operator:
, (Comma operator)
Example:
int a = (5, 10, 15); // Evaluates 5, then 10, then 15; a is assigned 15
11
9. Member Access Expressions
Definition: Member access expressions are used to access members (attributes or methods) of an object or
structure. They can use the dot operator or the arrow operator.
Operators:
Example:
struct Point {
int x;
int y;
1
};
Point p;
p.x = 10; // Direct access using dot operator
Point* ptr = &p;
ptr->y = 20; // Access using arrow operator
Sequential Control
Definition: Sequential control is the default mode of execution where statements are executed one after another
in the order they appear in the code.
AU
Example:
#include <iostream>
using namespace std;
int main() {
cout << "Step 1" << endl; // Executed first
cout << "Step 2" << endl; // Executed second
cout << "Step 3" << endl; // Executed third
return 0;
}
2. Decision-Making Structures
12
Definition: Decision-making structures allow the program to execute different blocks of code based on certain
conditions.
if Statement
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example:
int a = 3;
if (a > 5) {
1
cout << "a is greater than 5" << endl;
} else {
cout << "a is not greater than 5" << endl;
}
else-if Ladder
Syntax:
{
if (condition1) S1
Provides multiple conditions to test, allowing for more complex decision-making.
CC
// Code to execute if condition1 is true
}
else if (condition2)
{
// Code to execute if condition2 is true
}
else
{
AU
// Code to execute if none of the above conditions are true
}
Example:
int a = 7;
if (a > 10)
{
cout << "a is greater than 10" << endl;
}
else if (a > 5)
{
cout << "a is greater than 5 but not greater than 10" << endl;
}
else
13
{
cout << "a is 5 or less" << endl;
}
switch Statement
Allows multi-way branching based on the value of an expression. It is often used as an alternative to a
series of if-else statements.
Syntax:
switch (expression)
{
case value1:
// Code to execute if expression equals value1
1
break;
case value2:
// Code to execute if expression equals value2
}
break;
// more cases...
default:
Example:
S1
// Code to execute if expression does not match any case
CC
int day = 3;
switch (day)
{
case 1:
cout << "Monday" << endl;
break;
case 2:
AU
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
default:
cout << "Weekend" << endl;
}
3. LOOPING STRUCTURES
Looping structures repeatedly execute a block of code as long as a specified condition remains
true.
14
for Loop
Used for a known number of iterations. It initializes, tests, and updates the loop control variable
in a single line.
Syntax:
1
cout << "i = " << i << endl;
}
while Loop
while (condition)
{
// Code to execute
S1
Used for an unknown number of iterations. It evaluates the condition before executing the loop body.
Syntax:
CC
}
Example:
int i = 0;
while (i < 5)
{
cout << "i = " << i << endl;
++i;
}
AU
do-while Loop
Similar to while, but it evaluates the condition after executing the loop body, ensuring that the loop body
executes at least once.
Syntax:
do
{
// Code to execute
} while (condition);
Example:
int i = 0;
do
{
15
cout << "i = " << i << endl;
++i;
} while (i < 5);
4.Jump Statements
Jump statements control the flow of execution by breaking out of loops or jumping to other parts
of the code.
break Statement
Exits from the innermost loop or switch statement.
Syntax:
break;
Example:
for (int i = 0; i < 10; ++i) {
if (i == 5)
{
1
break; // Exits the loop when i equals 5
}
cout << "i = " << i << endl;
}
continue Statement
S1
Skips the remaining code in the current iteration of the loop and proceeds to the next iteration.
Syntax:
continue;
CC
Example:
return Statement
Exits from the current function and optionally returns a value to the caller.
Syntax:
return value; // Optional, can be omitted if the function has no return value
Example:
int add(int a, int b)
{
return a + b; // Returns the sum of a and b
16
}
UNIT –II
1. Define a class.
A class is a blueprint for creating objects in object-oriented programming. It defines a set of
attributes (data) and methods (functions) that encapsulate the behavior and state of the objects created
from it. Essentially, a class serves as a template for creating instances that share common characteristics
and functionalities.
2. What is an object?
An object is an instance of a class in object-oriented programming. It represents a specific entity
that encapsulates both data (attributes) and behavior (methods) defined by the class. Objects interact
1
with one another and can be manipulated through their methods, allowing for modular and organized
code.
3. How can we access the class members?
Class members (attributes and methods) can be accessed using the dot notation. For an object
S1
created from a class, you can access its members by using the syntax object_name.member_name. For
example, if obj is an instance of a class MyClass and it has an attribute attribute1 and a method
method1, you would access them as obj.attribute1 and obj.method1().
4. Write down a property of static member variable
A static member variable belongs to the class itself rather than to any specific instance. This
means that it is shared across all instances of the class, allowing for consistent access to a single value. Changes
CC
made to a static member variable affect all instances of the class, making it useful for tracking shared data, such
as a count of how many objects have been created.
A constructor is a special type of method in a class that is automatically called when an object is
instantiated. It initializes the object's attributes and prepares it for use.
AU
Special Characteristics of Constructors:
1. Same Name as Class: A constructor has the same name as the class it belongs to.
2. No Return Type: Constructors do not have a return type, not even void.
3. Automatic Invocation: They are called automatically when an object is created, without needing to be
invoked explicitly.
4. Overloading: A class can have multiple constructors with different parameters, allowing for different
ways to initialize an object.
6. What is a destructor?
A destructor is a special method in a class that is automatically called when an object is
destroyed or goes out of scope. Its primary purpose is to perform cleanup operations, such as releasing
resources, closing files, or deallocating memory that was allocated during the object's lifetime. Unlike
17
constructors, destructors typically have the same name as the class, prefixed with a tilde (~), and do not
take any parameters or return any values.
7. What is a friend function?
A friend function is a non-member function that has special access to the private and protected
members of a class. It is declared within the class using the keyword friend, allowing it to access the
class's internal data directly. Friend functions are useful for operations that involve multiple classes or
require access to the private attributes of a class without needing to be a member of that class.
Memory Efficiency: Bit fields allow for the storage of multiple boolean or small integer values within a
single byte or word, significantly reducing memory usage compared to using separate variables.
Control Over Data Representation: They provide fine-grained control over how data is represented
and packed in memory, making it easier to handle hardware-level programming or data communication
protocols where specific bit layouts are required.
1
9. What are all the limitations of bit fields?
Portability Issues: The representation and alignment of bit fields can vary between different
S1
compilers and architectures, leading to potential portability problems in code.
Limited Operations: Bit fields do not support all operations available for regular data types, such as
certain arithmetic or logical operations, and accessing them can be less efficient than using standard
types due to additional overhead for bit manipulation.
Defining Class
class ClassName
{
access_specifier:
// Body of the class
};
Example
class ThisClass
{
public:
int var; // data member
void print()
{
18
// member method
cout << "Hello";
}
};
1
S1
CC
Object in C++
When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, you need to create
objects.
Syntax to Create an Object
ClassName ObjectName;
Example
MyClass obj;
AU
2. Write about the data members and member function that exist in a class.
Data members are variables defined within a class that hold the state of an object. They can have
different access specifiers (public, private, protected) that determine their visibility outside the class.
class car
private:
public:
};
Member functions are functions defined within a class that operate on the data members. They
can be used to manipulate or access the state of an object and also define the behavior of that object.
class Car {
public:
1
void setModel(std::string m) { model = m; } // Setter
std::string getModel() const { return model; } // Getter
};
1. Memory Efficiency:
S1
3. Explain the advantage and disadvantages of bit fields.
Bit fields allow for the compact representation of data by allocating only the necessary
CC
number of bits, reducing overall memory usage. This is especially useful in applications like
embedded systems.
They provide precise control over how data is stored and represented in memory,
enabling the definition of data structures that match specific hardware or protocol requirements.
AU
3. Convenient Syntax:
Bit fields enable the declaration of multiple related flags or small integer values in a
single structure, simplifying code readability and maintenance.
1. Portability Issues:
The layout of bit fields can vary between different compilers and architectures, leading to
potential portability issues. The order of bits and padding may not be consistent across platforms.
2. Limited Operations:
20
Bit fields cannot be directly manipulated like regular variables. Operations like
incrementing or bitwise operations may require additional code, reducing efficiency.
3. Performance Overheads:
Accessing bit fields may introduce additional overhead due to the need for masking and
shifting operations, potentially leading to slower performance compared to using standard data
types.
An array of objects is declared similarly to a regular array, specifying the class type. Each element in the
array can be accessed and manipulated like any object.
1
Example:
class Student {
public:
};
std::string name;
int age;
void display() {
} S1
std::cout << "Name: " << name << ", Age: " << age << std::endl;
CC
int main() {
Student students[3]; // Array of 3 Student objects
students[0].name = "Alice";
students[0].age = 20;
students[1].name = "Bob";
students[1].age = 22;
students[2].name = "Charlie";
AU
students[2].age = 19;
Advantages
1. Easy Management: Arrays of objects simplify the management of multiple instances, making it
easy to loop through and perform operations on each object.
2. Memory Allocation: They provide contiguous memory allocation for objects, which can improve
cache performance and access speed.
21
3. Simplicity: Using arrays allows for cleaner and more organized code, especially when dealing with
large numbers of similar objects.
Disadvantages
1. Fixed Size: The size of the array must be known at compile time, limiting flexibility. Dynamic
resizing requires additional management, such as using pointers.
2. Complexity with Constructors: If the class has a constructor that requires parameters, initializing
an array of objects can become cumbersome.
3. Copying Issues: If an object is passed by value, it may lead to shallow copies unless a proper copy
constructor is implemented, which can introduce unintended side effects.
1
Destructor is a special member function that is automatically called when an object goes out of
scope or is explicitly deleted. Its primary purpose is to free resources that the object may have acquired
during its lifetime, ensuring proper cleanup and resource management.
S1
A destructor has the same name as the class but is preceded by a tilde (~). It cannot take
parameters and does not return a value.
CC
2. Automatic Invocation:
Destructors are automatically invoked when an object goes out of scope (e.g., at the end of a
block or when a dynamically allocated object is deleted) to ensure that resources are released.
3. Single Destructor:
Each class can have only one destructor, and it cannot be overloaded. This is because it must
AU
always have the same signature.
class MyClass
{
public:
~MyClass()
{
// Cleanup code here
}
};
Purposes of a Destructor
1. Resource Deallocation:
22
Destructors are commonly used to release memory that was allocated with new, close file
o
handles, or release other system resources (like network connections) when the object is no
longer needed.
2. Cleanup Operations:
o They can perform additional cleanup operations, such as resetting static members or logging
messages, before the object is destroyed.
Example:
class Example
{
public:
int* data;
Example(int size)
1
{
data = new int[size]; // Dynamic memory allocation
}
};
{
}
~Example()
int main()
S1
delete[] data; // Freeing allocated memory
CC
{
Example obj(10); // Destructor will be called automatically when obj goes out of scope
return 0;
}
1. Access Control:
Friend functions can access all members (private, protected, and public) of the class in
which they are declared as friends.
2. Not Members:
23
Despite their access rights, friend functions are not member functions. They are defined
outside the class scope and do not have a this pointer.
A class can have multiple friend functions, and friend functions can be friend to multiple
classes.
Friendship is not inherited. If a class is a friend of another class, derived classes do not
inherit this friendship.
Syntax
1
To declare a friend function, use the friend keyword inside the class definition.
Example
#include <iostream>
class Box {
S1
CC
private:
double width;
public:
AU
// Constructor
Box(double w) : width(w) {}
};
24
// Friend function definition
int main() {
1
return 0;
1. Class Declaration: S1
o The Box class has a private member width.
CC
2. Friend Function Declaration:
o printWidth(Box box); is declared as a friend of the Box class. This allows printWidth
to access the private member width.
3. Function Definition:
o The printWidth function is defined outside the class. It takes a Box object as an
argument and accesses its private member width directly.
4. Usage:
AU
o In the main function, an object of Box is created, and the printWidth function is
called, demonstrating that it can access the private member.
1. Violation of Encapsulation:
25
Overusing friend functions can lead to a violation of the encapsulation principle since
o
they have access to private members.
2. Maintenance:
o If a class changes its internal representation, it may require changes in all friend
functions that rely on its private members.
constructors are special member functions that are automatically called when an object of a class
is created. They are used to initialize the object's data members and set up any necessary resources.
There are several types of constructors, each serving different purposes. Here’s a detailed explanation of
the main types of constructors, along with examples.
1
1. Default Constructor
Example:
#include <iostream>
using namespace std; S1
defined, the compiler provides a default constructor.
CC
class Box
{
public:
double length;
// Default constructor
Box()
{
AU
length = 1.0; // Default length
}
};
int main()
{
Box box; // Default constructor is called
cout << "Length of box: " << box.length << endl; // Output: 1.0
return 0;
}
2. Parameterized Constructor
A parameterized constructor takes arguments to initialize an object with specific values. This
allows for more flexible and customized object creation.
26
Example:
#include <iostream>
using namespace std;
class Box
{
public:
double length;
// Parameterized constructor
Box(double l)
{
length = l;
}
};
1
int main()
{
Box box1(2.5); // Calls parameterized constructor
}
S1
Box box2(3.5); // Calls parameterized constructor
cout << "Length of box1: " << box1.length << endl; // Output: 2.5
cout << "Length of box2: " << box2.length << endl; // Output: 3.5
return 0;
3. Copy Constructor
CC
A copy constructor initializes a new object as a copy of an existing object. It takes a reference to
an object of the same class as its parameter.
Example:
#include <iostream>
using namespace std;
AU
class Box
{
public:
double length;
// Parameterized constructor
Box(double l)
{
length = l;
}
// Copy constructor
Box(const Box &b)
{
length = b.length; // Copying the value
27
}
};
int main()
{
Box box1(5.0); // Calls parameterized constructor
Box box2(box1); // Calls copy constructor
cout << "Length of box1: " << box1.length << endl; // Output: 5.0
cout << "Length of box2: " << box2.length << endl; // Output: 5.0
return 0;
}
4. Dynamic Constructor
A dynamic constructor allocates memory dynamically using new during object creation. This type
1
of constructor is useful when the size of the data members is not known at compile time.
Example:
#include <iostream>
class Box
{
S1
CC
public:
double *length;
// Dynamic constructor
Box(double l)
AU
*length = l;
~Box()
28
delete length; // Freeing allocated memory
};
int main()
1
return 0;
UNIT - III
PART – A (2 – MARK )
1. Define Operator overloading. S1
C++ has the ability to provide the operators with a special meaning for a data type, this ability is
CC
known as operator overloading. Operator overloading is a compile-time polymorphism. For example,
we can overload an operator '+' in a class like String so that we can concatenate two strings by just
using +.
2. List the operators which cannot be overloaded.
i. cope Resolution Operator (::)
ii. Member Access Operator (.)
iii. Pointer-to-Member Operator (.*)
iv. Sizeof Operator (sizeof)
AU
v. Conditional Operator (?:)
vi. Typeid Operator (typeid)
vii. New and Delete Operators (new, new[], delete, delete[]) can be overloaded, but the
global versions cannot be changed.
3. Give a function to overload a unary minus operator using friend class.
class unary
{
int a;
float b;
public:
Friend void operator ~(unary &);// Input and Output member functions
};
void operator ~(unary &)
{
s.a = - s.a;
29
s.b = - s.b;
}
int main()
{
unary u1, u2;
cout<<”\n UNARY MINUS OPRATOR OVERLOADING”;
u2=u1;
u2.putdata();
return 0;
}
1
5. How can objects be used as function arguments?
To pass an object as an argument we write the object name as the argument while calling the function
the same way we do it for other variables. Syntax: function_name(object_name);
6. Define inheritance.
S1
The capability of a class to derive properties and characteristics from another class is
called Inheritance.
7. What do you mean by single inheritance?
The inheritance in which a single derived class is inherited from a single base class is known as the
Single Inheritance
8. Differentiate between multilevel inheritance and multiple inheritance.
CC
Aspect Multilevel Inheritance Multiple Inheritance
Definition A type of inheritance where a class is derived from a A type of inheritance where a class can
class which is also derived from another class. inherit from more than one class. The
Essentially, it’s a “grandparent-parent-child” child class has multiple parent classes.
relationship.
Class Forms a linear inheritance hierarchy. A single Forms a branched inheritance
Relationship inheritance chain is formed from base to derived hierarchy. A single class inherits
classes. attributes and behaviours from multiple
AU
base classes.
Example Class C inherits from Class B, and Class B inherits Class C inherits from both Class A and
from Class A. Class B simultaneously.
1
An abstract class is a template that defines methods and variables for a category of objects or a specific
class. It's used to express general concepts that can be used as a basis for more specific classes.
12. What is the way to avoid the ambiguity in inheritance.
Ambiguity in inheritance can be defined as when one class is derived for two or more base classes then
S1
there are chances that the base classes have functions with the same name. So it will confuse derived
class to choose from similar name functions. To solve this ambiguity scope resolution operator is used
“::”.
Part – B ( 5 Mark)
CC
1. What is operator overloading? Write C++ program to add two complex numbers using operator
overloading.
Operator overloading in C++ is a compile-time polymorphism that helps give special meaning to
operators for a data type. The aim is to improve the usability of operators and the readability &
efficiency of the code.
#include <iostream>
#include <sstream>
#include <cmath>
AU
Using namespace std;
Class Complex{
private:
int real,imag;
public:
Complex(){
sreal = imag = 0;
}
Complex (int r, int i){
real = r;
imag = i;
}
string to_string(){
stringstream ss;
if(imag >= 0)
31
ss << "(" << real << " + " << imag << "i)";
else
ss << "(" << real << " - " << abs(imag) << "i)";
return ss.str();
}
Complex operator+(Complex c2){
Complex ret;
ret.real = real + c2.real;
ret.imag = imag + c2.imag;
return ret;
}
};
int main(){
Complex c1(8,-5), c2(2,3);
Complex res = c1 + c2;
1
cout << res.to_string();
}
S1
1. Syntax/Declaration Rule: While overloading a function we need to use the keyword operator ,
proceeded by class name and followed by operator symbol such as ‘+’.
1. Member and Non-member functions: We can overload operators in two ways:- first is as a member
functions , second is as a non-member functions. When overloading as a member function, the left
operand represents the object on which the function is called and when overloading as a non-member
function, we can specify any type for the left operand.
CC
1. Number of operands Required: Most operators can be overloaded with one or two operands. Example-
Unary operators like ++ require one operand, while binary operators like + require two operands.
1. Precedence and associativity: Operator precedence and associativity cannot be changed when
overloading operators. Example- It’s not allowed to change the precedence of (*) or the associativity of
(/).
1. Return type: When we overload operators than we must define the return type of the overloaded operator
function according to our need.
1. Friend function: If overloaded operators needs to access private member variables/functions of a class
AU
than they must be declared as a friend function.
1. Special Syntax: For operators like (), [], or -> we must use a special syntax when overloading. Example,
in order to overload the [] operator and to make objects callable like functions, we need to define a
function named operator().
32
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly
converted to unsigned), and overflow can occur (when long long is implicitly converted to float).
Explicit Type Conversion: This process is also called type casting and it is user-defined. Here the user can
typecast the result to make it of a particular data type.
In C++, it can be done by two ways:
Converting by assignment: This is done by explicitly defining the required type in front of the
expression in parenthesis. This can be also considered as forceful casting.
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
1
.
4. Explain the virtual base class in C++.
Virtual base classes are used in virtual inheritance in a way of preventing multiple “instances”
of a given class appearing in an inheritance hierarchy when using multiple inheritances.
S1
Need for Virtual Base Classes: Consider the situation where we have one class A . This class A is
inherited by two other classes B and C. Both these class are inherited into another in a new class D as
shown in figure below.
CC
AU
As we can see from the figure that data members/function of class A are inherited twice to class D.
One through class B and second through class C. When any data / function member of class A is accessed
by an object of class D, ambiguity arises as to which data/function member would be called? One
inherited through B or the other inherited through C. This confuses compiler and it displays error.
#include <iostream>
using namespace std;
class A {
public:
int a;
A() // constructor
{
a = 10;
33
}
};
int main()
{
D object; // object creation of class d
1
cout << "a = " << object.a << endl;
return 0;
}
S1
5. Distinguish between single and multiple inheritances.
CC
Inheritance is a method which can derive or construct new classes from the existing class. Here our main
topic of discussion is the difference between single inheritance and multiple inheritance, two types of
inheritance. In single inheritance, we do have only one base class, which is inherited by only one derived class.
In multiple inheritance we have more than two base class which are combinely inherited by only one derived
AU
class.
Comparison Chart
BASIS FOR
SINGLE INHERITANCE MULTIPLE INHERITANCE
COMPARISON
Basic Derived class inherits a Derived class inherits two or more than
single base class. two base class.
Implementation Class derived_class : Class derived _class: access_specifier
access_specifier base base_class1, access_specifier
class base_class2, ....
Access Derived class access the Derived class access the combined
features of single base features of inherited base classes
class
34
Visibility Public, Private, Protected Public, Private, Protected
Run time Require small amount of run Require additional runtime overhead as
time over head compared to single inheritance
1
Here,
class Complex {
S1
symbol - the operator we want to overload (+, <, -, ++, etc.)
CC
private:
double real;
double imag;
public:
// Constructor
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
AU
// Operator overloading for '+'
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
35
}
int main() {
Complex c1(3.0, 4.0); // 3 + 4i
1
Complex c2(1.5, 2.5); // 1.5 + 2.5i
c1.display();
cout << "c2: ";
c2.display(); S1
Complex c4 = c1 - c2; // Using overloaded -
cout << "Real part of c3: " << c3.getReal() << endl;
AU
cout << "Imaginary part of c3: " << c3.getImaginary() << endl;
return 0;
}
36
Syntax
class base_class_1
1
// class definition
};
S1
class derived_class: visibility_mode base_class_1
{
CC
// class definition
};
Description
A single derived_class inherits a single base_class. The visibility_mode is specified while declaring the derived
AU
class to specify the control of base class members within the derived class.
Example
#include <iostream>
// base class
class electronicDevice
37
{
public:
electronicDevice()
1
};
// derived class
{ S1
CC
public:
Computer()
AU
{
};
int main()
38
// create object of the derived class
return 0;
Multiple Inheritance
The inheritance in which a class can inherit or derive the characteristics of multiple classes, or a derived class
can have over one base class, is known as Multiple Inheritance. It specifies access specifiers separately for all
1
the base classes at the time of inheritance. The derived class can derive the joint features of all these classes and
the data members of all the base classes are accessed by the derived or child class according to the access
specifiers.
S1
CC
Syntax
class base_class_1
AU
// class definition
};
class base_class_2
// class definition
39
};
// class definition
};
Description
The derived_class inherits the characteristics of two base classes, base_class_1 and base_class_2. The
1
visibility_mode is specified for each base class while declaring a derived class. These modes can be different
for every base class.
Example
#include <iostream>
class electronicDevice
{
AU
public:
electronicDevice()
40
};
// class_B
class Computer
public:
Computer()
1
{
};
}
cout << "I am a computer.\n\n";
S1
CC
// class_C inheriting class_A and class_B
{};
AU
int main()
// will be called
41
return 0;
Multilevel Inheritance
The inheritance in which a class can be derived from another derived class is known as Multilevel Inheritance.
Suppose there are three classes A, B, and C. A is the base class that derives from class B. So, B is the derived
class of A. Now, C is the class that is derived from class B. This makes class B, the base class for class C but is
the derived class of class A. This scenario is known as the Multilevel Inheritance. The data members of each
respective base class are accessed by their respective derived classes according to the specified visibility modes.
1
S1
CC
Syntax
class class_A
{
AU
// class definition
};
// class definition
};
42
class class_C: visibility_mode class_B
// class definition
};
Description
The class_A is inherited by the sub-class class_B. The class_B is inherited by the subclass class_C. A subclass
inherits a single class in each succeeding level.
1
Example
#include <iostream>
// class_A S1
CC
class electronicDevice
public:
AU
// constructor of the base class 1
electronicDevice()
};
43
// class_B inheriting class_A
public:
Computer()
1
cout << "I am a computer.\n\n";
};
}
public:
AU
// constructor of the derived class
Linux_based()
};
44
int main()
return 0;
1
3. Explain Hierarchical, Hybrid and Multipath inheritances.
Hierarchical Inheritance
S1
The inheritance in which a single base class inherits multiple derived classes is known as the Hierarchical
Inheritance. This inheritance has a tree-like structure since every class acts as a base class for one or more child
classes. The visibility mode for each derived class is specified separately during the inheritance and it accesses
the data members accordingly.
CC
AU
Syntax
class class_A
// class definition
45
};
// class definition
};
1
// class definition
};
{ S1
CC
// class definition
};
// class definition
};
Description
The subclasses class_B and class_C inherit the attributes of the base class class_A. Further, these two
subclasses are inherited by other subclasses class_D and class_E respectively.
Example
46
The following example illustrates Hierarchical Inheritance in C++:
#include <iostream>
// base class
class electronicDevice
public:
1
// constructor of the base class 1
electronicDevice()
S1
cout << "I am an electronic device.\n\n";
CC
}
};
{};
{};
int main()
47
{
return 0;
1
Hybrid Inheritance
Hybrid Inheritance, as the name suggests, is the combination of two or over two types of inheritances. For
example, the classes in a program are in such an arrangement that they show both single inheritance and
hierarchical inheritance at the same time. Such an arrangement is known as the Hybrid Inheritance. This is
S1
arguably the most complex inheritance among all the types of inheritance in C++. The data members of the base
class will be accessed according to the specified visibility mode.
CC
AU
Syntax
class class_A
// class definition
};
48
class class_B
// class definition
};
// class definition
1
};
// class definition S1
CC
};
{
AU
// class definition
};
Description
The derived class class_C inherits two base classes that are, class_A and class_B. This is the structure of
Multiple Inheritance. And two subclasses class_D and class_E, further inherit class_C. This is the structure of
Hierarchical Inheritance. The overall structure of Hybrid Inheritance includes more than one type of inheritance.
Example
49
#include <iostream>
// base class 1
class electronicDevice
public:
1
electronicDevice()
} S1
cout << "I am an electronic device.\n\n";
CC
};
// base class 2
class Computer
AU
{
public:
Computer()
50
}
};
{};
1
{};
int
main()
{ S1
CC
// create an object of the derived class
Multipath inheritance
The multipath inheritance happens when there is a derived class inheriting the attributes of 2 superclasses, and
these superclasses have a common base class. The following diagram represents the structure of a diamond
problem.
51
In a multipath inheritance when the two classes class_1 and class_2 inherit the same base class, it creates two
1
copies of the Base_class. So when an object of the derived_class accesses a member of the base class, it causes
ambiguity. This ambiguous situation is caused because it is unclear which copy of the base_class member needs
to be accessed. And in such a situation the compiler throws an error.
#include <iostream>
class Base_class
{
AU
public:
int x;
};
// class 1
52
public:
int y;
};
// class 2
public:
1
int z;
};
// derived class 3
S1
class derived_class : public class_1, public class_2
CC
{
public:
int sum;
AU
};
int main()
derived_class obj;
53
obj.y = 20;
obj.z = 30;
cout << "The sum is: " << obj.sum << "\n\n";
return 0;
1
4. Explain the abstract class mechanism with suitable example.
In programming, an abstract class in C++ has at least one pure virtual function by definition. In other
words, a function that has no definition. The abstract class's descendants must define the pure virtual function;
S1
otherwise, the subclass would become an abstract class in its own right.
Abstract classes are used to express broad concepts from which more concrete classes can be derived. An
abstract class type object cannot be created. To abstract class types, however, you can
use pointers and references. Declare at least one pure virtual member feature when creating an abstract class.
The pure specifier (= 0) syntax is used to declare a virtual function.
CC
Take a look at the example in virtual functions. The aim of the class is to provide general functionality
for shape, but objects of type shape are much too general to be useful. Shape is therefore a suitable candidate for
an abstract class:
Syntax:
AU
C-lass classname //abstract class
//data members
public:
/* Other members */
};
54
Characteristics of Abstract Class in C++
2. Abstract Classes cannot be instantiated, but pointers and references of Abstract Class types can be
created. You cannot create an object of an abstract class. Here is an example of a pointer to an abstract
class.
3. Abstract Classes are mainly used for Upcasting, which means its derived classes can use its interface.
4. Classes that inherit the Abstract Class must implement all pure virtual functions. If they do not, those
classes will also be treated as abstract classes.
class Shape {
public:
// All the functions of both square and rectangle are clubbed together in a sigle class.
1
void width(int w) {
shape_width = w;
}
void height(int h) {
shape_height = h;
}
int areaOfSquare(int s) {
return 4 * s;
}
int areaOfRectange(int l, int b) {
return (l * b);
S1
CC
}
protected:
int shape_width;
int shape_height;
};
int main (){
shapes R;
R.width(5);
AU
R.height(10);
cout<<"The area of rectangle is"<<R.areaOfRectangle";
return 0;
}
UNIT 4
PART A (2 marks)
1. Define compile time and run time polymorphism.
55
Compile-time polymorphism is implemented through method overloading, which allows
multiple methods with the same name but different parameters and return types. Run-time
polymorphism is implemented through method overriding, where different classes can have the same
method with the same parameters.
2. Name two types of polymorphism in C++.
The two types of polymorphism in C++ are compile-time and run-time polymorphism
3. Define virtual function.
A virtual function is a member function that you expect to be redefined in derived classes. When
you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual
function for that object and execute the derived class's version of the function.
4. Define pointer.
Pointers are symbolic representations of addresses. They enable programs to simulate call-by-
reference as well as to create and manipulate dynamic data structures.
SYNTAX:
datatype *var_name;
1
int *ptr;
5. What is a pure virtual function
A pure virtual function or pure virtual method is a virtual function that is required to be
implemented by a derived class if the derived class is not abstract. Classes containing pure virtual
SYNTAX:
S1
methods are termed "abstract" and they cannot be instantiated directly.
The "this" pointer is a special pointer in C++ that points to the object that is currently executing a
member function. It's a hidden pointer that's automatically passed to member functions by the
compiler. The "this" pointer is used for a variety of purposes, including: Accessing data members,
CC
Returning the object itself, and Comparing objects.
7. Define array.
Array is a linear data structure where all elements are arranged sequentially. It is a collection of elements of
same data type stored at contiguous memory locations
8. Mention the types of array
There are majorly 4 types of arrays
1. Fixed Size Array
2. Dynamic Sized Array
AU
3. 1-Dimensional Array
4. Multi-Dimensional Array
9. What is one dimensional array.
A One-Dimensional Array is the simplest form of an Array in which the elements are stored
linearly and can be accessed individually by specifying the index value of each element stored in the
array.
10. What is two dimensional array.
Two-dimensional arrays or multi-dimensional arrays are arrays where the data element's position
is referred to, by two indices. The name specifies two dimensions, that is, row and column.
11. What is late binding.
Dynamic binding is a programming concept that determines which method to invoke at runtime,
rather than at compile time.
56
Virtual functions are special types of member functions in a class that can be modified in
subclasses
PART B(5 MARKS)
13. Explain about pointers to class objects.
A pointer to an object in C++ is a variable that contains an object's memory address. Pointers
provide indirect access to and control over memory items. They are especially helpful when we need to
dynamically allocate memory for objects, build linked lists or trees, or pass objects by reference to methods
without making duplicates.
The behavior of an object pointer is identical to that of a variable pointer. But in this case,
the object's address is kept instead of the variables. When a class object is formed in the main function, a
pointer variable is declared similarly to the variable itself. Using a data type for the pointer is not
recommended when generating a pointer to an object. Instead, we must make use of the object pointer's
class name. The -> symbol must be used to call a class member function using a Pointer in the main
1
function.
Syntax:
S1
We declare a pointer to an object using the object's class name followed by an asterisk (*) and
the pointer name.
CC
ClassName *pointer name; // Declaration of a pointer to an object
Creating Objects and Pointers:
Objects are created using the new keyword, which dynamically allocates memory for the object.
After that, the Pointer is assigned the memory address of the newly created object.
ClassName *objPtr = new ClassName(); // Creating an object and assigning its address to the pointer
AU
Accessing Object Members via Pointer:
We can use the arrow operator (->) to access members (variables and functions) of the object
through the pointer.
int two_d_array[10][5]
The two-dimensional array can be referred to as one of the simplest forms of a multidimensional array.
#include <iostream>
using namespace std;
// Main function.
int main()
{
1
int mat[3][3];
}
for (int j = 0; j < 3; j++)
{
}
cin >> mat[i][j];
S1
CC
// Making a line break.
cout << endl;
return 0;
}
Insert the values of the matrix:
1
2
3
4
5
6
7
58
8
9
1 2 3
4 5 6
7 8 9
1
memory block.
Syntax
Here is the syntax of the new operator in C++ language.
Example
1. Pointer_name=new datatype;
59
16. Explain the virtual functions
A virtual function (also known as virtual methods) is a member function that is declared within a
base class and is re-defined (overridden) by a derived class. When you refer to a derived class object
using a pointer or a reference to the base class, you can call a virtual function for that object and execute
the derived class’s version of the method
Virtual functions ensure that the correct function is called for an object, regardless of the type of
reference (or pointer) used for the function call.
They are mainly used to achieve Runtime polymorphism.
Functions are declared with a virtual keyword in a base class.
The resolving of a function call is done at runtime.
Rules for Virtual Functions
The rules for the virtual functions in C++ are as follows:
1. Virtual functions cannot be static.
1
2. A virtual function can be a friend function of another class.
3. Virtual functions should be accessed using a pointer or reference of base class type to achieve runtime
polymorphism.
4. The prototype of virtual functions should be the same in the base as well as the derived class.
function is used.
S1
5. They are always defined in the base class and overridden in a derived class. It is not mandatory for the
derived class to override (or re-define the virtual function), in that case, the base class version of the
6. A class may have a virtual destructor but it cannot have a virtual constructor.
A derived class is a class that takes some properties from its base class.
It is true that a pointer of one class can point to another class, but classes must be a base and derived class,
then it is possible.
To access the variable of the base class, a base class pointer will be used.
So, a pointer is a type of base class, and it can access all, public function and variables of the base class
since the pointer is of the base class, this is known as a binding pointer.
60
In this pointer base class is owned by the base class but points to the derived class object.
The same works with derived class pointer, values are changed.
Example:
// C++ program to Demonstrate the
// implementation of the base class
// pointer pointing to derived class
#include <iostream>
using namespace std;
// Base Class
class BaseClass {
public:
int var_base;
1
// class members
void display()
{
cout << "Displaying Base class"
};
}
// Driver Code
int main()
{
// Pointer to base class
BaseClass* base_class_pointer;
BaseClass obj_base;
DerivedClass obj_derived;
base_class_pointer->var_base = 34;
base_class_pointer->var_base = 3400;
1
base_class_pointer->display();
DerivedClass* derived_class_pointer;
derived_class_pointer = &obj_derived;
}
derived_class_pointer->var_base = 9448;
derived_class_pointer->var_derived = 98;
derived_class_pointer->display();
return 0;
Output
S1
CC
Displaying Base class variable var_base: 34
Displaying Base class variable var_base: 3400
Displaying Base classvariable var_base: 9448
Displaying Derived class variable var_derived: 98
AU
62
where,
data_type: is a type of data of each array block.
array_name: is the name of the array using which we can refer to it.
array_size: is the number of blocks of memory array going to have.
For Example
int nums[5];
2. Two-dimensional (2D) array:
Multidimensional arrays can be considered as an array of arrays or as a matrix consisting of rows and
columns.
1
where,
S1
Syntax for Declaration of Two-Dimensional Array
Below is the syntax to declare the Two-dimensional array
data_type array_name[sizeof_1st_dimension][sizeof_2nd_dimension];
3D array
63
Syntax for Declaration of Three-Dimensional Array
Below is the syntax to declare the Three-dimensional array
data_type array_name[sizeof_1st_dimension][sizeof_2nd_dimension][sizeof_3rd_dimension];
where,
data_type: is a type of data of each array block.
array_name: is the name of the array using which we can refer to it.
sizeof_dimension: is the number of blocks of memory array going to have in the corresponding
dimension.
For Example
int nums[5][10][2];
19. Explain the run time polymorphism using virtual functions with suitable examples.
1
A virtual function is a member function that is declared in the base class using the
keyword virtual and is re-defined (Overridden) in the derived class. It tells the compiler to perform
late binding where the compiler matches the object with the right called function and executes it
during the runtime. This technique falls under Runtime Polymorphism.
S1
The term Polymorphism means the ability to take many forms. It occurs if there is a hierarchy of
classes that are all related to each other by inheritance. In simple words, when we break down
Polymorphism into ‘Poly – Many’ and ‘morphism – Forms’ it means showing different characteristics
in different situations.
CC
AU
Class Hierarchy
Note: In C++ what calling a virtual functions means is that; if we call a member function then it
could cause a different function to be executed instead depending on what type of object invoked it.
Because overriding from derived classes hasn’t happened yet, the virtual call mechanism is
disallowed in constructors. Also to mention that objects are built from the ground up or follows a
bottom to top approach.
Consider the following simple program as an example of runtime polymorphism. The main thing to
note about the program is that the derived class’s function is called using a base class pointer.
The idea is that virtual functions are called according to the type of the object instance pointed to or
referenced, not according to the type of the pointer or reference.
In other words, virtual functions are resolved late, at runtime.
/ C++ program to demonstrate how we will calculate
64
// area of shapes without virtual function
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
// parameterized constructor
Shape(int l, int w)
{
length = l;
width = w;
}
int get_Area()
{
1
cout << "This is call to parent class area\n";
// Returning 1 in user-defined function means true
return 1;
}
protected:
};
int length, width;
// Derived class
class Square : public Shape {
S1
CC
public:
Square(int l = 0, int w = 0)
: Shape(l, w)
{
} // declaring and initializing derived class
// constructor
int get_Area()
{
AU
cout << "Square area: " << length * width << '\n';
return (length * width);
}
};
// Derived class
class Rectangle : public Shape {
public:
Rectangle(int l = 0, int w = 0)
: Shape(l, w)
{
} // declaring and initializing derived class
// constructor
int get_Area()
{
cout << "Rectangle area: " << length * width
65
<< '\n';
return (length * width);
}
};
int main()
{
Shape* s;
1
s->get_Area();
s = &rec; // reference variable
s->get_Area();
2 Marks:
S1
return 0; // too tell the program executed
// successfully
UNIT-V
CC
1. What is File?
File is the collection of related records stored in a disk.
2. What are the types of files?
There are three types :
• Sequential File
• Random File
• Indexed Sequential file
AU
3. What is sequential file?
The records of the sequential files can be accessed one by one or sequentially.
4. What is indexed Sequential file?
The records of the index sequential file can be access randomly as well as sequentially .
5. What is the name of Header file supports file classes?
The header file <fstream.h> contains all file supporting classes
such as ifstream in // input
ofstream out // output
fstream io // input and output
6. What is Random Access?
Random Access is the method of accessing a record from the file in any order.
7. What are the functions used for random accessing?
The random accessing can be done using the functions
66
• Seekg()
• Seekp()
8. What is the purpose of seekg() function?
The seekg() function is used to move get pointer(input) to a specified
location. Example:
Infile.seekg(10);
It moves the file pointer to the byte 10.
9. What is the purpose of seekp() function?
The seekp() is used to move the put pointer(output) to a specified
location. Example:
Outfile.seekp(m) where m is the bytes.
1. . What is Virtual Function?
A Virtual function is a member function that is declared within a base class and
1
redefined by a derived class. To create a virtual function , the function declaration
should be preceded with a keyword Virtual.
A virtual function can be called just like any other member function . The more interesting
feature of virtual function is , it is capable of supporting run-time polymorphism.
Example:
Virtual void fun()
S1
CC
AU
67
{
function statements;
}
Rules for Virtual function:
1. The virtual function must be members of some class
2. They cannot be static members
3. A virtual function can be a friend of another class
4. They are accesses by using object pointers
5. If a virtual function is defined in the base class, it need not be necessarily
redefined in the derived class.
2. What is Exception Handling?
Exception Handing is a built-in mechanism to handle error during run time. It si more
useful to manage and respond run time errors.
1
The exception handling is built upon three keywords
a. Try
b. Catch c.
Syntax:- Try
{
{
// try block
}
catch(type1 arg)
Throw
S1
CC
// catch blcok
}
catch(type2 arg)
`{
// catch block
}
AU
.
.
.catch(typen arg)
{
// catch block
}
3. Define stream in c++?
• The I/O systems supplies an interface to the programmer that is independent of the actual
device accessed.
• This interface is known as stream.
• A stream is a sequence of bytes.
i)input stream- the source stream that provide data to the program
68
ii)output stream- the destination stream that receives output from the program
13.Define c++ stream classes?•
C++ contains a hierarchy of
classes that are used to define
various streams.
• These classes are called stream classes
• Its declared inthe header file”iostream in all the programs.
1. Define put() and get() functions?
The stream class define two member functions to handle I/O
operations. i)Get()
ii)Put()
There are two types of get() functions
Get(char*) – assigns input character to its argument
Get(void) – returns input character
2. What is the use of Getline() and write () functions?
1
Getline() – reads a whole line of text that ends with a new line character.
Cin.getline(line,size);
Cin.getline(name,20);
Write() – displays an entire line
Cout.write(line,size)
Cout(string1,10);
3. Define width() fiunction?
S1
It used to define the width of a field for the output of an item.
It can specify the field width for only one item.
Cout.width(w);
CC
Cout.width(5);
W – field width(number of columns)
4. What is template?
• It can be used to create a family of classes and functions.
• Template is defined within parameter.
• Templates are sometimes called parameterized classes or functions.
Template<class T>
AU
Calss classname
{
……….
};
5. Write the steps for file operations?
1. Suitable name of file
2. Data type and structure
3. Purpose
4. Opening Method
5 Marks:
1
S1
• C++ contains a set of classes that defines the file handling methods.
• These include ifstream, ofstream and fstream.
• These classes are derived from fstreambase and form the corresponding iostream class.
• These classes ,designed to manage the disk files are declared in fstream
• This file is included in any program that uses files.
2. Explain File Pointers and Manipulators?
CC
- Each file has two pointers known as file pointers,
- one is called the input pointer and the other is called output pointer.
- The input pointer is used for reading the contents of of a given file location
- The output pointer is used for writing to a given file location
Default actions:
- When a file is opened in read-only mode,the input pointer is automatically set at
the beginning to read from the start
AU
- when a file is opened in write-only mode the existing contents are deleted
Functions for Manipulations of File pointer:
seekg() Moves get pointer (input)to a specified location.
seekp() Moves put pointer (output) to a specified
location. tellg() Give the current position of the get
pointer.
tellp() Give the current position of the put pointer.
Specifying the Offset:
‘Seek’ functions seekg() and seekp() can also be used with two arguments
as follows:
seekg (offset,refposition);
seekp (offset,refposition);
three constants defined in the ios class:
70
• ios::beg Start of file
• ios::cur Current position of the pointer
• ios::end End of file3. Explain about Sequential Input and Output
Operations:
- The file stream classes support a number of member functions for performing the input
and output operations on files.
- One pairs of functions,put() and get() are designed for handling a single character at a
time.
- Another pair of functions, write(),read() are designed to write and read blocks of
binary data.
a) put() and get() Functions:
-The function put() writes a single character to the associated stream.
-The function get() reads a single character from the associated stream.
b) write() and read () functions:
- The functions write() and read() handle the data in binary form.
1
- An int character takes two bytes to store its value in the
binary form,irrespective of its size
- The binary input and output functions takes the following form:
infile.read (( char * ) & V,sizeof (V));
S1
outfile.write (( char *) & V ,sizeof (V));
- These functions take two arguments.
- The first is the address of the variable V
- The second is the length of that variable in bytes.
- The address of the variable must be cast to type char*(i.e pointer to
character type).
CC
#include <iostream.h>
#include <fstream.h>
#include<string.h>
int main()
{
char string[80]; cout<<”enter
a string \n”; cin>>string;
AU
71
There are many problems encounterd while dealing with files like
• a file which we are attempting to open for reading does not exist.
• The file name used for a new file may already exist.
• We are attempting an invalid operation such as reading past the end of file.
• There may not be any space in the disk for storing more data.
• We may use invalid file name.
The function clear() resets the error state so that further operations can be attempted
Error Handling Functions
1
S1
CC
Example:
………….. ifstream
infile;
infile.open(“ABC”);
while(!infile.fail())
{
AU
1
• The input data are separated by white spaces
• The operator >> reads the data character by character
• For example consider the
S1
code int code;
cin>> code;
• Suppose the following data is entered as input 42580
• the operator will read the characters upto 8 and the value 4258 is assigned to code
• general form of displaying data on the screen is
cout <<item1<<item2<<…………<<item n
CC
put() and get() functions:-
• The classes istream and ostream define two member functions get(),put()
• to handle the single character input/output operations
• There are two types of get() functions.
get(char *) -- assigns the input character to its argument
get(void) -- returns the input character.
Example
AU
Char c;
cin.get( c ) //get a character from the keyboard and assigns it to c
while( c!=’\n’)
{
cout<< c; //display the character on screen
cin.get( c ) //get another character
}
• this code reads and display a line of text.
• The operator >> can be used to read a character but it will skip the white spaces and
newline character
• The function put(), a member of ostream class can be used to output a line of text,
character by character.
For example
73
cout.put(‘x’); -- displays the character x
cout.put(ch); -- displays the value of variable ch.
cout.put(68); -- displays the character D.This statement will convert the numeric
value 68 to a char value and displays character whose
ASCII value is 68.
Example for get() and put():-
#include <iostream>
using namespace
std; int main()
{
int count=0;
char c;
cout<<”INPUT TEXT \n”;
cin.get( c );
while ( c 1=’\n’ )
1
{ cout.put( c);
count++;
cin.get( c );
}
} Input
Object oriented programming
Output
Object oriented programming
S1
cout<< “\n Number of characters =” <<count <<”\n”;
return 0;
CC
Number of characters=27
getline() and write() functions:-
• The getline() function reads a whole line of text that ends with a newline
character.
cin.getline(line,size);
• This function call invokes the function getline() which reads character input into
the variable line.
AU
74
• This input will be read correctly and assigned to the character array name.
• Let us suppose the input is as
follows: Object Oriented
Programming
• In this case ,the input will be terminated after reading the following 19 characters
Object Oriented Pro
• The write() function displays an entire line and has the following form:
cout.write(line,size)
• The first argument line represents the name of the string to be displayed
• the second argument size indicates the number of characters
Example for getline and write():-
# include <iostream.h>
# include <conio.h>
# include <string.h>
1
main()
{
char str[20];
clrscr();
int n=strlen(str);
for (int i=0;i<=n;i++)
{
cout.write(str,i);
S1
cout<<"PLEASE ENTER THE STRING:->";
cin.getline(str,20);
CC
cout<<"\n";
}
for(i=n;i>0;i--)
{
cout.write(str,i);
cout<<"\n";
}
AU
}
2. Describe about all the file related functions used in C++ Language.
To perform file I/O operation. We must include a header file <fstream.h> which
contains all classes supports file operations.
Ifstream class: (input file operation)
This calss provides input operations or methods which contains open(), getline(), get(),
read(), tellg(), seekg().
Example :
Ifstrem f1; Fstream
infile;
f1.open(“employee.
dat”);
75
ofstream class: (output file operation)
This class provides output operations it supports the following methods.
Open( )
tell( )
Put( )
write( )
Seek( )
Example:
Ofstream outfile;
Outfile open (“student-dat”);
fstream class:
It provides all function supports I/O operation.
1
File operation:
1. Opening the file
2. Checking the file
3. Reading / writing the file
4. Processing the records
5. Closing the records
6. Closing the file.
Opening the file:
S1
File can be opened using the open() method.
CC
Syntax Filestream-class object
name; Object-
name.open(“File
name”);
Example
Ofstream f1;
f1.open(“student.Dat”);
AU
76
}
Writing a file: -
file processing; The data can be written in a file using.
File.object<<data1<<end1<<data2<<end1<<data3<<endl;
Example :
ofstream f1; f1.open(“student.Dat”);
f1<<a1<<endl<<a2<<endl<<a3<<endl;
Reading file
The data can be read from the file using
File object>>data1>>data2>>data3;
Example
f1>>a1>>a2;
Processing the records:
Records can be processed by using any mathematical and logical operations.
Closing the file:
1
File object.close();
3. Illustrate some of an File Handling Problems.
a.Write a program to create file number dat on disk to store 10 records which
contains tow numeric numbers.
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{
ofstream f1;
S1
CC
f1.open("number.dat");
cout<<"Give Data1";
cin>>a1;
cout<<"Give Data2:";
cin>>a2;
f1<<a1<<endl<<a2<<endl;
}
f1.close();
getch();
}
b.Write a program to create a file called “student.dat” to store rno, name, m1, m2, m3,
m4,m5 for ten students.
#include<iostream.h>
77
#include<fstream.h>
#include<conio.h>
void main( )
{
ofstream f1
f1.open(“student.dat”);
int rno;
char name[15];
int m1, m2, m3, m4, m5;
for (i=1; i<=10; i++)
{
cout<<”Give rno<<“Give name”<<endl;
cout<<”Give marks” <<endl;
cin>>rno>>name>>endl;
cin>>m1>>m2>>m3>>m4>>m5;
1
f1<<m1 <<m2<<m3<<m4<<m5<<endl;
}
f1.close();
}
and
find the sum.
#include<iostream.h>
#include<fstream.h>
S1
c.Write a program to read a file “number.dat” which contains records of two numbers
CC
#include<conio.h>
void main()
{
clrscr();
ifstream f1;
f1.open("number.dat");
AU
1
cout<<"Give emp NO";
cin>>eno; cout<<"Give
Name:"; cin>>nam;
cout<<"Give Baic [ay:";
cin>>basic; cout<<"Give
Da:";
cin>>hra;
cin>>da;
cout<<"Give Hra:"; S1
f1<<eno<<endl<<nam<<endl<<basic<<endl<<da<<endl<<hra<<endl;
CC
} f1.close();
getch();
}
e.Write a program to read the “payroll.dat” file to find gross pay for each employee.
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
AU
void main()
{
clrscr(); ifstream f1;
f1.open("payroll.dat");
int eno;
char nam[10]; float
basic; float da;
float hra;
float gross
while(!f1.eof())
{
f1>>eno>>nam>>basic>>da>>hra;
79
gross=basic+da+hra
cout<<endl;
cout<<"Employee No:"<<eno<<endl;
cout<<"Employee Name:"<<nam<<endl;
cout<<"Basic Pay :"<<basic<<endl;
cout<<"Hra :"<<hra<<endl;
cout<<"DA :"<<da<<endl;
cout<<"Gross pay :"<<gross<<endl;
} f1.close();
getch();
}
1
binary data on disk it consumer very less disk memory.
If we want to write records in Binary format we have to open the file in binary mode by using
the
I/O operations read and write.
Read ():-
file. Syntax :
S1
This function is used to read record in a binary form from a
Program to create a binary file to store ten records of students and read them
.
AU
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{
clrscr();
struct student
{ int rno;
char nam[15];
int age;
float ht;
};
80
struct student stud; ofstream f1;
f1.open("student.dat",ios::binary);
for(int i=1;i<=5;i++)
{
cout<<"Give Roll No:";
cin>>stud.rno;
cout<<"Give Name
:"; cin>>stud.nam;
cout<<"Give Age :";
cin>>stud.age;
cout<<"Give Ht :";
cin>>stud.ht;
f1.write((char *) &stud,sizeof(struct student));
}
f1.close();
1
}
};
struct student stud;
int sum=0;
float aage;
ifstream f1;
f1.open("student.dat",ios::binary);
while(!f1.eof())
{
f1.read((char*) &stud,sizeof(struct student));
cout<<"The Roll No:"<<stud.rno<<endl;
cout<<"The Name :"<<stud.nam<<endl;
81
cout<<"The Age :"<<stud.age<<endl;
cout<<"The Height :"<<stud.ht<<endl<<endl;
sum=sum+stud.age;
}
f1.close();
aage=sum/10;
cout<<"The Average Age:"<<aage;
getch();
}
1
S1
CC
AU
82