Object Oriented Programming Using C++
Object Oriented Programming Using C++
Object Oriented Programming Using C++
technology and industry and includes the all-round personal development of students including
To provide high quality technical and managerial manpower, information and consultancy services
to the industry and community to enable the industry and community to face the changing
We, at MSBTE are committed to offer the best- i n - c l a s s academic services to the students
and institutes to enhance the delight of industry and society. This will be achieved through
development, implementation, evaluation and monitoring system along with adequate faculty
development programs.
for
Object Oriented
Programming Using C++
(313304)
Semester-III
(BD/IF/CO/CM/CW/HA/IH/TE)
Maharashtra State
Board of Technical Education, Mumbai
(Autonomous) (1SO:9001:2015) (1SO/IEC 27001:2013)
Maharashtra State Board of Technical Education,
(Autonomous) (ISO:9001: 2015) (ISO/IEC 27001 : 2013)
4th Floor, Government Polytechnic Building, 49, Kherwadi,
Bandra ( East ), Mumbai - 400051.
(Printed on July, 2024)
MAHARASHTRA STATE
BOARD OF TECHNICAL EDUCATION
Certificate
This is to certify that Mr. / Ms......................................................
. . . . . . . . . . . . . . . . . . . . .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . of Institute,
(Inst. Code: ...............) has completed the term work satisfactorily in course
Object Oriented Programming Using C++ (313304) for the academic year
Subject Teacher
Head of the Department Principal
Seal of
Institution
Object Oriented Programming Using C ++ (313304)
Preface
The primary focus of any engineering laboratory/ field work in the technical
education system is to develop the much-needed industry relevant competencies
and skills. With this in view, MSBTE embarked on this innovative 'I' Scheme curricula
for emerging diploma programs with outcome-based education as the focus and
accordingly, relatively large amount of time is allotted for the practical work. This
displays the great importance of laboratory work making each teacher; instructor and
student to realize that every minute of the laboratory time need to be effectively utilized
to develop these outcomes, rather than doing other mundane activities. Therefore, for the
successful implementation of this outcome-based curriculum, every practical has been
designed to serve as a 'vehicle' to develop this industry identified competency in every
student. The practical skills are difficult to develop through 'chalk and duster' activity
in the classroom situation. Accordingly, the 'I' scheme laboratory manual development
team designed the practical’s to focus on the outcomes, rather than the traditional old
practice of conducting practical’s to 'verify the theory' (which may become a byproduct
along the way).
This laboratory manual is designed to help all stakeholders, especially the students,
teachers and instructors to develop in the student the pre-determined outcomes. It is
expected from each student that at least a day in advance, they have to thoroughly read
through the concerned practical procedure that they will do the next day and understand
the minimum theoretical background associated with the practical. Every practical in this
manual begins by identifying the competency, industry relevant skills, course outcomes
and practical outcomes which serve as a key focal point for doing the practical. The
students will then become aware about the skills they will achieve through procedure
shown there and necessary precautions to be taken, which will help them to apply in
solving real-world problems in their professional life.
This manual also provides guidelines to teachers and instructors to effectively
facilitate student- centered lab activities through each practical exercise by arranging and
managing necessary resources in order that the students follow the procedures and
precautions systematically ensuring the achievement of outcomes in the students.
In the modern world of Information technology, the Object Oriented Programming
has become the most preferred approach for software development. It offers a powerful
way to cope up with complexity of real-world problems. Among the OOP languages
available, C++ is the primitive language which develops fundamental understanding of
Object Oriented Concepts. This course enables students to develop programs in 'C++'
using Object Oriented Programming approach.
Although best possible care has been taken to check for errors (if any) in this
laboratory manual, perfection may elude us as this is the first edition of this manual. Any
errors and suggestions for improvement are solicited and highly welcome
PO1: Basic and Discipline specific knowledge: Apply knowledge of basic mathematics, science
and engineering fundamentals and engineering specialization to solve the engineering problems.
PO2: Problem analysis: Identify and analyze well-defined engineering problems using codified
standard methods.
PO3: Design/ development of solutions: Design solutions for well-defined technical problems
and assist with the design of systems components or processes to meet specified needs.
PO4: Engineering Tools, Experimentation and Testing: Apply modern tools and appropriate
PO5: Engineering practices for society, sustainability and environment: Apply appropriate
engineering activities.
PO7: Life-long learning: Ability to analyse individual needs and engage in updating in the context
of technological changes.
The aim of this course is to help the student to attain the student to attain the following industry
identified outcomes through various teaching learning experiences:
• Develop ‘C++’ programs using classes and objects.
• Develop an application by implementing Inheritance.
• Develop an application by using Polymorphism.
• Use appropriate File handling operations for developing applications.
Guidelines to Teachers
1. There will be two sheets of blank pages after every practical for the student
to report other matters (if any), which is not mentioned in the printed practicals.
2. For difficult practicals if required, teacher could provide the demonstration of
the practical emphasizing of the skills which the student should achieve.
3. Teachers should give opportunity to students for hands-on after the demonstration.
4. Assess the skill achievement of the students and COs of each unit.
5. One or two questions ought to be added in each practical for different batches.
For these teachers can maintain various practical related question bank for each
course.
6. For effective implementation and attainment of practical outcomes, teacher ought
to ensure that in the beginning itself of each practical, students must read through
the complete write- up of that practical sheet.
7. During practical, ensure that each student gets chance and takes active part in
taking observations/ readings and performing practical.
8. Teacher ought to assess the performance of students continuously according to
the MSBTE guidelines.
Note: Kindly do add specific instructions for students for effective implementation of
practical' s depending upon your course, if needed.
1. For incidental writing on the day of each practical session every student
should maintain a dated log book for the whole semester, apart from this
laboratory manual which has to submit for assessment to the teacher in the
next practical session.
2. For effective implementation and attainment of practical outcomes, in the
beginning itself of each practical, students need to read through the complete
write-up including the practical related questions and assessment scheme of
that practical sheet.
3. Student ought to refer the reference books, lab manuals, etc.
4. Student should not hesitate to ask any difficulties they face during the
conduct of practical' s.
Dated
Assess sign.
Date of Date of
- ment
Sr. Page perfor submit- of Remarks
No Practical Outcome No. marks (if any)
mance ssion teach
(25)
er
I Practical Significance:
This practical is useful for students to evaluate expressions using different types of operators
and Input/output functions. Students will be able to evaluate any type of expressions in the
C++ program.
Develop program to evaluate expressions using various operators and Input/output functions.
Operators in C++:
An operator is a symbol that operates on a value to perform specific mathematical or logical
computations. They form the foundation of any programming language. In C++, we have
built-in operators to provide the required functionality.
An operator operates the operands. For example,
int c = a + b;
Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.
Different types of operators are:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators
C++ I/O operation is using the stream concept. Stream is the sequence of bytes or
flow of data. It makes the performance fast. If bytes flow from main memory to
device like printer, display screen, or a network connection, etc, this is called as
output operation.
If bytes flow from device like printer, display screen, or a network connection, etc
to main memory, this is called as input operation.
Header File Function and Description
<iostream> It is used to define the cout, cin and cerr objects,
which correspond to standard output stream, standard
input stream and standard error stream, respectively.
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1. Write a C++ code to evaluate following expression using input output function:
y= 5*x-5 where value of x is taken from user. Find the value of y.
2. Write a program to print “hi” msg if entered value is more than 10 otherwise print “bye” msg
on output screen. (Use of Relational operator)
3. Write a program to print largest number among two number using Conditional operator.
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
………………………………………………………………………………………………………
..……………………………………………………………………………………………………..
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
XIV Practical Related Questions
Note: Below given are few sample questions for reference. Teacher must design
more such questions so as to ensure the achievement of identified CO.
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
float r = 2;
float circle;
circle= 2 *PI* r;
cout << circle;
return 0;
}
b) #include <iostream>
int main()
{
int x;
x=(3/2) + 2;
cout<<"Value of x is : "<<x;
return 0;
}
c) #include <iostream>
int main()
{
int x;
int y=9;
x=y +int(10.0);
cout<<"Value of x : "<<x;
return 0;
}
I Practical Significance:
This practical is useful for students to access the global variable, creation of dynamic memory
allocation and displaying output in proper format. Students will be able to use different C++
operators in programming.
• New operator
A new operator is used to create the object while a delete operator is used to delete the
object. When the object is created by using the new operator, then the object will exist until we
explicitly use the delete operator to delete the object. Therefore, we can say that the lifetime of
the object is not related to the block structure of the program
The above syntax is used to create the object using the new operator.
In the above syntax, 'pointer_variable' is the name of the pointer variable, 'new' is the
operator, and 'data-type' defines the type of the data.
Example 1:
int *p;
p = new int;
In the above example, 'p' is a pointer of type int.
• Delete operator
When memory is no longer required, then it needs to be deallocated so that the memory
can be used for another purpose. This can be achieved by using the delete operator, as shown
below:
delete pointer_variable;
In the above statement, 'delete' is the operator used to delete the existing object, and
'pointer_variable' is the name of the pointer variable.
In the previous case, we have created pointer 'p' by using the new
operator, and can be deleted by using the following statements:
delete p;
Manipulators are helping functions that can modify the input/output stream. It does not
mean that we change the value of a variable, it only modifies the I/O stream using insertion
(<<) and extraction (>>) operators.
Manipulators are special functions that can be included in the I/O statement to alter the format
parameters of a stream. Manipulators are operators that are used to format the data display.
To access manipulators, the file iomanip.h should be included in the program.
cout<<”object”<<endl<<”Oriented”<<endl<<”Programming”;
• setw Manipulator:
The word ‘setw’ in C++ stands for set width. Furthermore, the use of the setw C++
manipulator takes place to set the output’s field width on the output device. Moreover, by
default, the displaying or printing of the output takes place right-justified within the specified
field of setw C++ manipulators.
The use of the setw manipulator takes place to set the width of the output in a program.
Furthermore, it takes up an argument ‘n’, the width of the field in which the displaying of the
output is to take place. Moreover, the output in the field, by default, is right-aligned.
setw(n)
The ‘n’ indicates the field width that is the number of columns and it happens to be
an integer value. Also, if the specified field width is less in comparison to the width of the
output data’s width that is to be displayed, then the effect of setw manipulator will not take
place. Moreover, there will be a normal displaying or printing of the output.
The setw C++ manipulator is also a component of “iomanip.h” header file. Furthermore,
the inclusion of this header file must take place in the program to use setw manipulator.
Some important manipulators in <iomanip> are:
• setw (val): It is used to set the field width in output operations.
• setfill (c): It is used to fill the character ‘c’ on output stream.
• setprecision (val): It sets val as the new value for the precision of floating-point values.
• setbase(val): It is used to set the numeric base value for numeric values.
• setiosflags(flag): It is used to set the format flags specified by parameter mask.
• resetiosflags(m): It is used to reset the format flags specified by parameter mask.
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
XI Precautions to be followed
XII Exercise:
1. Write a C++ Program which show the use of function outside the class using scope resolution operator.
2. Write a program to display the massage “Welcome to the world of C++” using manipulators.
3. Write a program to create the memory using new operator and free the created memory using delete
operator.
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
……………………………………………………………………………………………………..
..........................................................................................................................................................
............................................................................................................................................................
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
1. Write a C++ program to access the global variable using scope resolution operator.
class A {
public:
// Only declaration
void fun();
};
int main()
{
A a;
a.fun();
return 0;
}
c. #include <iostream>
#include <iomanip>
2.https://www.javatpoint.com/cpp-manipulator-setw-function
This practical is useful for students to get accurate result while solving any expressions. Student
will be able to use different types of type casting.
A type cast is basically a conversion from one type to another. There are two types of type
conversion:
o Implicit Type Conversion.
o Explicit Type Conversion.
1. Implicit Type Conversion Also known as ‘automatic type conversion’. Done by the
compiler on its own, without any external trigger from the user. Generally takes place
when in an expression more than one data type is present. In such condition type
conversion (type promotion) takes place to avoid loss of data.
All the data types of the variables are upgraded to the data type of the variable with
largest data type.
• bool -> char -> short int -> int ->
• unsigned int -> long -> unsigned ->
• long long -> float -> double -> long double
2. 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.
Syntax:
(type) expression;
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1. Find the area of the rectangle by casting double data into float and int type.
2. Write a program which show the use of implicit type casting to calculate the average of
two number
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
……………………………………………………………………………………………………..
..……………………………………………………………………………………………………
Maharashtra State Board of Technology (K Scheme) 14
Object Oriented Programming Using C++ (313304)
…..………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
2. Write a program which display the percentage of students which accept marks of three
subjects from user.(Show the use of Implicit type casting)
3.Complete the following table:
1. https://www.javatpoint.com/type-casting-in-cpp
2.https://www.programiz.com/cpp-programming/type
I Practical Significance:
The classes and objects help to represent real life entity with different attributes and related
Member functions.
Declaring Objects: 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:
className ObjectName;
eg.
Student std;
Accessing data members and member functions: The data members and member
functions of class can be accessed using the dot('.') operator with the object.
For example if the name of object is std and you want to access the member
function with the name getData() then you will have to write std.getData() .
Member Functions in Classes: There are two ways to define functions that belongs to a class:
Class Methods: A member function of a class can also be defined inside the class. However,
when a member function is defined inside the class, the class name and the scope resolution
operator are not specified in the function header. Moreover, the member functions defined
inside a class definition are by default inline functions called.
In the following example, we define a function inside the class, and we name it "myMethod".
Note: You access methods just like you access attributes; by creating an object of the class and
using the dot syntax (.):
Inside Example
class MyClass
{ // The class
public: // Access specifier
void myMethod()
{
// Method/function defined inside the class
cout << "Hello World!";
}
};
Maharashtra State Board of Technology (K Scheme) 19
Object Oriented Programming Using C++ (313304)
int main()
{
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
……………………………………………………………………………………………………..
..……………………………………………………………………………………………………
..……………………………………………………………………………………………………
...........................................................................................................................................................
..........................................................................................................................................................
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
1. Define a class Room with data members length, breadth and height. Member function
calculate_area () and calculate_volume(). Calculate the area and volume of room. Define the
member function inside the class.
2. Define a class mean in which assign two numbers in assign member function (i.e.
assign(4,8)) passed value from main function and define assign member function inside the
class and display the mean of two number on output screen.
I Practical Significance:
The classes and objects help to represent real life entity with different attributes and related
Member functions.
Member Functions in Classes: There are two ways to define functions that belongs to a class:
}
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
1.#include<iostream.h>
class Class_name{
public:
};
2. #include <iostream>
class Sq {
public:
int a;
int square(); // Declaring function square with no argument and having
return type 'int'.
};
int Sq::square()
{
return a * a;
}
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
………………………………………………………………………………………………………
............................................................................................................................................................
............................................................................................................................................................
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
XIV Practical Related Questions
Note: Below given are few sample questions for reference. Teacher must design
more such questions so as to ensure the achievement of identified CO.
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
1. Write a program to find area of circle such that the class circle must have three functions
namely:
2. Define a class complex with data members real and imaginary, member function read()
and write(). Write a program to perform the addition of two complex number and display the
result.
I Practical Significance:
The classes and objects help to represent real life entity with different attributes and
related member functions. The use of inline functions facilitates faster execution of
the program
Inline Function: C++ inline function is concept that is commonly used with
classes. If a function is inline, the compiler places a copy of the code of that
function at each point where the function is called at compile time.
A function definition in a class definition is an inline function definition, even
without the use of the inline keyword.
To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function. The compiler can
ignore the inline qualifier in case defined function is more than a line.
Declaring inline function:
Syntax:
class className
{
//other members declaration public:
inline return type FunctionName(list of parameters)
{
//body of inline function
}
//other members declaration
Maharashtra State Board of Technology (K Scheme) 29
Object Oriented Programming Using C++ (313304)
};
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1. Write a C++ program to create a class "Number" having data members n1 and n2 and perform
mathematical operations like addition, subtraction, multiplication and division on two
numbers using inline functions.
X C++ code:
1. Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
……………………………………………………………………………………………………..
..……………………………………………………………………………………………………
…..…………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
Maharashtra State Board of Technology (K Scheme) 30
Object Oriented Programming Using C++ (313304)
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
a) #include <iostream>
using namespace std;
class Sample {
public:
inline void myfun();
};
void inline Sample::myfun()
{
cout << "Hello from inline function";
}
int main()
{
Sample S;
S.myfun();
return 0;
}
2. https://www.codesdope.com/cpp-inline-function/
• External Function
I Practical Significance:
The classes and objects help to represent real life entity with different attributes
and related member functions.
The use of friend function allows non-member functions to access the private
and protected data of the class.
Friend function is widely used in cases when two or more classes contain the
interrelated members relative to other parts of the program.
III Course Level Learning Outcome(s)
public:
friend return type friendFunctionName(list of parameters);
//other members declaration
};
return type friendFunctionName(list of parameters)
{
//body of friend function
}
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system
System
basic configuration for each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1. Write a C++ program to exchange the values of two variables using friend function.
2. WAP to create two classes test1 and test2 which stores marks of a student. Read value for
class objects and calculate average of two tests using friend function.
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
……………………………………………………………………………………………………..
..……………………………………………………………………………………………………
..……………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
void show()
{
Box b(10);
cout<<"Value of capacity
is: "<<b.capacity<<endl;
}
2. https://www.tutorialspoint.com/cplusplus/cpp_friend_functions.htm
3. https://www.geeksforgeeks.org/friend-class-function-cpp/
I Practical Significance:
A typical use of static members is for recording data common to all objects of a class.
Static data member as a counter to store the number of objects of a particular class type
that are created.
Static data member in C++ can be accessed anywhere in the program after the
declaration of class either using the class instance or using scope resolution, class
name, and variable name
• Static data members are class members that are declared using static keywords. A static
member has certain special characteristics which are as follows:
Only one copy of that member is created for the entire class and is shared by all the objects of that
class, no matter how many objects are created.
It is initialized before any object of this class is created, even before the main starts.
It is visible only within the class, but its lifetime is the entire program.
• Declaring Static Data Member-
Syntax:
static data_type data_member_name;
• The static member functions are special functions used to access the static data members or
other static member functions. A member function is defined using the static keyword. A static
Maharashtra State Board of Technology (K Scheme)
38
Object Oriented Programming Using C++ (313304)
member function shares the single copy of the member function to any number of the class'
objects. We can access the static member function using the class name or class' objects.
• Declaring Static Data Member-
Syntax-
class_name::function_name (parameter);
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1. Write a Program to define a class having data members principal, duration and rate of interest.
Declare rate _of_ interest as static member variable .calculate the simple interest and display it.
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
……………………………………………………………………………………………………..
..……………………………………………………………………………………………………
..……………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
Maharashtra State Board of Technology (K Scheme)
39
Object Oriented Programming Using C++ (313304)
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
1. Write a Program to calculate weight of object at different planets using formula weight=m*g
Where m=mass of object G=gravitational force Declare g as static member variable.
class Test
{
private: static int x;
public: static void fun()
{
cout << ++x
<< “ ”;
}
};
int Test :: x =20;
void main()
{
Test x;
x.fun();
x.fun();
}
class Result
{
static Test a;
public:
Result()
{
cout <<
"Result's Constructor is Called "
<< endl;
}
};
void main()
{
Result b;
}
2 https://www.geeksforgeeks.org/cpp-static-data-members/
I Practical Significance:
The classes and objects help to represent real life entity with different attributes and
related member functions.
Array of objects are used to represent the data of similar type.
The array of objects represent storing multiple objects in a single name. Reduce the time and
memory by storing the data in a single variable.
Write/ Compile/ debug/ Execute simple C++ program using classes and array of
objects.
Declaring Array of
Objects: Syntax:
className ObjectArrayName[size];
eg.
Student std[5];
Accessing data members and member functions: The data members and member
functions of class can be accessed using the dot('.') operator with the object.
For example if the name of object is std[2] and you want to access the member
function with the name getDataO then you will have to write std[2].getData0.
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
Write a C++ program to declare class ‘Account’ having data members as Account_No and
Balance. Accept this data for 10 accounts and display data of Accounts having balance greater
than 10000.
X C++ code:
1 Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
…………………………………………………………………………………………………………
…………………………………………………………………………………………………………
…………………………………………………………………………………………………………
……………….……………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
……
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
1. Write a Program to declare a class birthday having data member day, month and year.
Accept this info for object using pointer to array of object and display it.
#include<iostream>
using namespace std;
class Employee
{
int id;
char name[30];
public:
void getdata();
void putdata();
};
void Employee::getdata()
{
cout << "Enter Id : ";
cin >> id;
cout << "Enter Name : ";
cin >> name;
}
void Employee::putdata()
{
cout << id << " ";
cout << name << " ";
cout << endl;
}
int main()
{
Maharashtra State Board of Technology (K Scheme) 45
Object Oriented Programming Using C++ (313304)
Employee emp[30];
int n, i;
cout << "Enter Number of Employees - ";
cin >> n;
for(i = 0; i < n; i++)
emp[i].getdata();
examples/
• Default Constructor
• Parameterized Constructor
• Copy Constructor
• Multiple Constructor in one class
I Practical Significance:
The classes and objects help to represent real life entity with different attributes and
related member functions.
The use of constructor functions facilitates initialization of instance variables.
Constructor is to set the initial values of the object's attributes or perform any action that
needs to be done for each object.
• Declaring constructor
function: Syntax:
class className
{
//other members
Maharashtra State Board of Technology (K Scheme) 48
Object Oriented Programming Using C++(313304)
declaration public:
className(list of parameters)
{
I/body of constructor function
}
//other members declaration
};
• Parameterized Constructor In
C++
Syntax of Parameterized Constructor
class ClassName {
public:
ClassName(Type1 parameter1, Type2 parameter2, ...); // Parameterized
//constructor declaration
};
• Copy Constructor In C++
Syntax of Copy Constructor
class ClassName {
public:
ClassName(const ClassName& obj); // Copy constructor declaration
};
VII Resources Required
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1. WAP to implement default constructor that initializes num1 and num2 as 10 and 20 and prints
the values of num1 and num2.
Maharashtra State Board of Technology (K Scheme) 49
Object Oriented Programming Using C++(313304)
2. Define a class student which contain member variables as rollno ,name and course. Write a program
using constructor as "Computer Engineering" for course . Accept this data for objects of class and
display the data.
X C++ code:
1. Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
……………………………………………………………………………………………………..
..……………………………………………………………………………………………………
..……………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
1. WAP to declare a class student having datamembers as name and percentage .Write
constructor to initialise these data members. Accept and display data for one object.
2. WAP to declare class time having data members as hrs, min,sec. Write a constructor
to accept data and display for two objects.
#include <iostream>
#include <string>
using namespace std;
class A{
mutable int a;
public:
A(){
cout<<"Default
constructor called\n";
}
A(const A& a){
cout<<"Copy
Constructor called\n";
}
};
int main(int argc, char const
*argv[])
{
A obj;
A a1 = obj;
A a2(obj);
}
#include <iostream>
#include <string>
using namespace std;
class A{
int a;
public:
A(int i){
a = i;
}
void assign(int i){
a = i;
}
int return_value(){
return a;
}
Maharashtra State Board of Technology (K Scheme) 51
Object Oriented Programming Using C++(313304)
};
int main(int argc, char const
*argv[])
{
A obj;
obj.assign(5);
cout<<obj.return_value();
}
1. https://www.geeksforgeeks.org/constructors-c/
2. https://www.javatpoint.com/cpp-tutorial
I Practical Significance:
The use of inheritance shows the reusability of the existing class properties
and deriving a new class with additional properties.
Multiple Inheritances is a feature of C++ where a class can inherit from more
than one classes.
Constructor is to set the initial values of the object's attributes or perform any
action that needs to be done for each object.
Single Inheritance
Pictorial Representation:
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1. WAP to implement inheritance shown below figure. Assume suitable member function.
2. Write a C++ program to define a class "Employee" having data members emp_no,
emp_name and emp_designation. Derive a class "Salary" from "Employee" having data
members basic, hra, da, gross_sal. Accept and display data for one employee.
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
……………………………………………………………………………………………………..
..……………………………………………………………………………………………………
..……………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
1. Write a C++ program to define a class "Student" having data members roll_no,
name. Derive a class "Marks" from "Student" having data members ml,m2,m3,
total and percentage. Accept and display data for one student.
a) #include<iostream.h>
class Base
public:
Base(){}
~Base(){}
protected:
private:
};
class Derived:public Base
{
public:
Derived(){}
Derived(){}
private:
protected:
};
void main()
b) #include <iostream.h>
class A
{
public:
void print() {
cout <<
"print() in A";
}
};
class B :
private A
{
public:
void print() {
cout <<
"print() in B";
}
};
class C :
public B
{
public:
void print() {
cout <<
"print() in C";
A::print();}
};
void main()
{
Cb; b.print();
}
1.https://www.geeksforgeeks.org/constructors-c/
2.https://www.javatpoint.com/cpp-tutorial
I Practical Significance:
Multiple Inheritances is a feature of C++ where a class can inherit from more
than one classes.
Multiple inheritance allows you to mix properties and behaviors from different
classes.
Syntax:
class derived_class_name: virtual visibility_mode base_class
{
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1. Identify the following type of Inheritance shown . Write a definition of each class .Write suitable
member functions to accept and display data for each class.
2. Write a Program to get the average marks of six subjects using the Multiple Inheritance
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
……………………………………………………………………………………………………..
..……………………………………………………………………………………………………
..……………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
return 0;
}
1. https://www.geeksforgeeks.org/constructors-c/
2. https://www.javatpoint.com/cpp-tutorial
I Practical Significance:
Hierarchical Inheritance allows for code reuse and refactoring, as the same code can
be reused in multiple classes.
1. Inheritance :-It is the process of inheriting properties of objects of one class by objects
of another class. The class which inherits the properties of another class is called
Derived or Child or Sub class and The class whose properties are inherited is called
Base or Parent or Super class.
Class A
{
............
};
Class B: access_specifier A
{
Maharashtra State Board of Technology (K Scheme) 68
Object Oriented Programming Using C++(313304)
.........
};
Class C: access_specifier A
{
.............
};
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1. Write a C++ program to implement the following inheritance. Accept and display data for one
programmer and one manager. Make display function virtual.
2. An Educational institute wishes to store the data of its employees. The Hierarchical relationships
of its related classes are shown in the figure below. Define all the classes to represent hierarchy
and define functions to retrieve individual information as and when required.
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
……………………………………………………………………………………………………..
..……………………………………………………………………………………………………
..……………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
XIV Practical Related Questions
Note: Below given are few sample questions for reference. Teacher must
design more such questions so as to ensure the achievement of identified CO.
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
a) #include <iostream>
using namespace std;
class Animal {
public:
void info() {
cout << "I am an animal." <<
endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "I am a Dog. Woof
woof." << endl;
}
};
class Cat : public Animal {
public:
void meow() {
cout << "I am a Cat. Meow." <<
endl;
}
};
int main() {
class
Dog dog1;
cout << "Dog Class:" << endl;
dog1.info(); // parent Class function
dog1.bark();
class
Cat cat1;
cout << "\nCat Class:" << endl;
cat1.info(); // parent Class function
cat1.meow();
return 0;
}
b)#include<iostream.h>
#include<conio.h>
class emp
{
int id;
char name[20];
int sal;
public:
void accept()
{
cout<<"enter id, name and salary"<<endl;
cin>>id>>name>>sal;
}
void dis()
{
cout<<"id"<<id;
cout<<"name--"<<name<<endl;
cout<<"salary"<<sal;
}
};
class manager : public emp
{
public:
acc1()
{
accept();
dis();
}
};
class clerk :public emp
{
public: acc2()
{
accept();
dis() ;
}
};
void main()
{
manager m;
clerk c;
m.acc1();
c.acc2();
getch();
}
(Space for Answers)
1. https://www.javatpoint.com/hierarchical-inheritance-in-cpp
2. https://www.geeksforgeeks.org/cpp-hierarchical-inheritance/
3. https://www.w3schools.in/cplusplus/inheritance
I Practical Significance:
Virtual Base Class is that a child class could have duplicate sets of members inherited
from a single base class.
Virtual base classes used to prevent multiple instances of a given class from
appearing in an inheritance hierarchy when using multiple inheritances.
Write/ Compile/ debug I Execute simple C++ program using Virtual Base
Class.
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1. Write a C++ program to implement the concept of Virtual Base Class for following
figure.
Assume suitable data and function members.
2. Write a C++ program to implement the concept of Virtual Base Class for following
figure.
Accept and Display information of one employee with his name,code,basic
Pay,Experience and Gross Salary with the object of Employee class.
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
………………………………………………………………………………………………………
..……………………………………………………………………………………………………
..……………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
1.Write a C++ program to implement the concept of virtual base class for
following figure.
2.Write a C++ program to implement given figure class hierarchy. Assume suitable
member variables and member functions.
int count;
};
Struct b
Maharashtra State Board of Technology (K Scheme) 78
Object Oriented Programming Using C++(313304)
{
int* value;
};
struct c
public a,
public b
};
int main()
{
c* p new =c;
p->value=0;
cout<< "Inherited";
return 0;
}
b)#include<iostream.h>
class A
{
public:
void display()
{
cout<< “A\n”;
};
class B : public A
{
public:
void display()
{
cout<<”B\n”;
}
};
int main()
{
B b;
b.display();
b.A::display();
b.B::display();
return 0;
}
1. https://www.geeksforgeeks.org/virtual-base-class-in-c/
2. https://www.w3schools.in/cplusplus/virtual-function
Practical No.15: Write programs which show use of constructors in derived class.
I Practical Significance:
Constructors in derived classes are special member functions used to initialize objects of
derived classes. When you create an object of a derived class, its constructor is called to
initialize both the base class part and the derived class part of the object
When a derived class is extended from the base class, the constructor of the base class is
executed first followed by the constructor of the derived class.
Syntax:
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
// base class
class Parent
{
public:
// sub class
class Child : public Parent
{
public:
return 0;
}
2. #include <iostream>
using namespace std;
public:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
………………………………………………………………………………………………………
..……………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
a)class Base1{
int data1;
public:
Base1(int i){
data1 = i;
cout<<"Base1 class constructor
called"<<endl;
}
void printDataBase1(void){
cout<<"The value of data1 is
Maharashtra State Board of Technology (K Scheme) 84
Object Oriented Programming Using C++(313304)
"<<data1<<endl;
}
};
class Base2{
int data2;
public:
Base2(int i){
data2 = i;
cout << "Base2 class constructor
called" << endl;
}
void printDataBase2(void){
cout << "The value of data2 is " <<
data2 << endl;
}
};
b) #include <iostream>
c) using namespace std;
class A
{
public:
A(int n )
{
cout << n;
}
};
Maharashtra State Board of Technology (K Scheme) 85
Object Oriented Programming Using C++(313304)
class B: public A
{
public:
B(int n, double d)
: A(n)
{
cout << d;
}
};
class C: public B
{
public:
C(int n, double d, char ch)
: B(n, d)
{
cout <<ch;
}
};
int main()
{
C c(5, 4.3, 'R');
return 0;
}
1. https://www.tutorialspoint.com/cplusplus/cpp_constructor_destructor.htm
2. https://www.codewithharry.com/videos/cpp-tutorials-in-hindi-48/
VI Assessment Scheme
I Practical Significance:
The pointer to objects helps to improve the efficiency of the program and access
the objects dynamically.
Pointers to objects: -
A pointer is a variable that stores the memory address of another variable (or object) as
its value. A pointer aims to point to a data type which may be int, character, double,
etc.
Pointers to objects aim to make a pointer that can access the object, not the variables.
Pointer to object in C++ refers to accessing an object.
There are two approaches by which you can access an object. One is directly and the
other is by using a pointer to an object in C++.
A pointer to an object in C++ is used to store the address of an object. For creating a
pointer to an object in C++, we use the following syntax:
For storing the address of an object into a pointer in c++, we use the following syntax:
The above syntax can be used to store the address in the pointer to the object. After
storing the address in the pointer to the object, the member function can be called using
the pointer to the object with the help of an arrow operator.
Examples
Example 1. In the below example, a simple class named My_Class is created. An object
of the class is defined as named object. Here a pointer is also defined named p. In the
program given below program, it is shown how can we access the object directly and
how can we use the pointer to access the object directly.
#include <iostream>
using namespace std;
class My_Class {
int num;
public:
void set_number(int value)
{
num = value;
}
void show_number();
};
void My_Class::show_number()
{
cout << num << "\n";
}
int main()
{
My_Class object, *p; // an object is declared and a pointer to it
return 0;
}
In C++ programming, this is a keyword that refers to the current instance of the class. There
can be 3 main usages of this keyword in C++.
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1. State output of the following code:
#include <iostream.h>
#include<conio.h>
class myclass
{
int i;
public:
void read(int j)
{
i= j;
}
int getint()
{
return i;
}
};
void main()
{
clrscr();
rnyclass ob, *objectPointer;
Maharashtra State Board of Technology (K Scheme) 90
Object Oriented Programming Using C++ (313304)
objectPointer = &ob;
objectPointer->read(lO);
cout<<objectPointer->getint();
getch();
2. Which is the pointer which denotes the object calling the member function?
a. Variable pointer b) This pointer
c) Null pointer d) Zero pointer
a) Null b) zero
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
………………………………………………………………………………………………………
..…………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
I Practical Significance:
The key feature of class inheritance is that a pointer to a derived class is type-
compatible with a pointer to its base class.
.
Let we have-
class base { .. . };
base *pl;
derived d_obj;
pl=&d_obj;
ll
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
a) Null b) zero
c)Address of an object of same type d) All of them
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
………………………………………………………………………………………………………
..…………………………………………………………………………………………………
..…………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
2. Write a program which show the use of Pointer to derived class in multilevel
inheritance.
int main()
{
base b;
base *bptr;
cout<<"Pointer of base class points to it";
bptr=&b;
bptr->n1=44;
bptr->show();
derived d;
cout<<"\n";
bptr=&d;
bptr->n1=66;
bptr->show();
return 0;
}
Maharashtra State Board of Technology (K Scheme) 98
Object Oriented Programming Using C++ (313304)
b) #include <iostream.h>
class BaseClass {
int x;
public:
void setx(int i)
X = i;
int getx()
return x;
};
int gety()
{
return y;
}
};
int main()
{
BaseClass *p;
BaseClass baseObject;
DerivedClass derivedObject;
p = &baseObject;
p->setx(l0);
cout << "Base object x: "<< p->getx() <<"\n" ;
p = &derivedObject;
p->setx(99);
derivedObject.sety(88);
cout << "Derived object x: " << p->getx () <<"\n" ;
cout << "Derived object y: "<< derivedObject.gety() << '\n';
return 0;
}
Practical No.18: Write programs which show the use of function overloading
I Practical Significance:
The concept of function overloading helps to use more than one definition for a function
name in the same scope and helps to extend the concept of polymorphism.
.
Syntax
class class_Name
{
retumtype method()
Maharashtra State Board of Technology (K Scheme) 101
Object Oriented Programming Using C++ (313304)
{
}
returntype method(datatype1 variable1)
{
}
returntype method(datatype1 variable1, datatype2 variable2)
{
}
};
Examples
void display(); //function with no arguments
void display( int); //function with one integer type arguments void display(
float); //function with one floating point arguments
void display( int, float); //function with one floating and one integer type
argument
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
………………………………………………………………………………………………………
..…………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or attach more
pages if needed.)
1. Write a C++ Program to interchange the values of two int , float and
char using function overloading.
2. Write a C++ Program that find the sum of two int and double number
using function overloading.
2. https://www.javatpoint.com/cpp-overloading
I Practical Significance:
The concept of operator overloading helps to assign the new meaning to the
existing operator and helps to extend the concept of polymorphism.
Syntax:
//Statements;
Maharashtra State Board of Technology (K Scheme) 107
Object Oriented Programming Using C++ (313304)
}
The operator keyword is used for overloading the operators.
▪ In the case of a non-static member function, the unary operator should not have
an argument.
▪ In the case of a friend function, the unary operator should have only one
argument.
▪ They perform various operations such as incrementing/decrementing a value
by one, negating an expression, or inverting the value of a boolean
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
public:
// required constructors Distance()
{
feet= 0;
inches= 0;
Distance(int f, inti)
feet= f;
inches= i;
void displayDistance() {
cout << "F: "<<feet<<" I:"<< inches <<endl;
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
………………………………………………………………………………………………………
..……………………………………………………………………………………………………
..……………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
Write a C++ program to overload unary operators (++) increment and (--) decrement
by using member function and friend function.
1. Write C++ program to find the area of various geometrical shapes by
function overloading. (eg. Area of circle, circumference of circle etc…)
a)#include<iostream.h>
class 3D
{
int x, y, z;
public:
3D (int a=O, int b=O, int c=O)
{
x=a;
y=b;
z = c;
}
3D operator++()
{
X=X + 1;
y=y + 1;
z=z + 1;
return *this;
}
3D operator ++(int)
{
3D t = *this;
X=X + 1;
y = y + 1;
z = z + 1;
return t;
}
3D show()
{
cout<<"The elements are:\n" cout<<"x:"<<this-x<<",
y:<<this-y <<",z:"<<this-z;
};
int main()
{
3D pt1(2,4,5), pt2(7,1,3);
cout<<"Point one's dimensions before increment are:"<<
ptl.show();
++ptl;
cout<<"Point one's dimensions after increment are:"<<
ptl.show();
cout<<"Point two's dimensions before increment are:"<<
pt2.show();
pt2++;
Maharashtra State Board of Technology (K Scheme) 111
Object Oriented Programming Using C++ (313304)
cout<<"Point two's dimensions after increment are:"<<
pt2.show();
return 0;
}
b) #include <iostream.h>
// C++ program to show unary
// operator overloading
#include <iostream>
using namespace std;
class Distance {
public:
int feet, inch;
// Constructor to initialize
// the object's value
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// Overloading(-) operator to
// perform decrement operation
// of Distance object
void operator-()
{
feet--;
inch--;
cout << "\nFeet & Inches(Decrement): " <<
feet << "'" << inch;
}
};
// Driver Code
int main()
{
Distance d1(8, 9);
I Practical Significance:
For example, suppose we have two numbers, 5 and 6; and overload the binary (+) operator.
So, the binary (+) operator adds the numbers 5 and 6 and returns 11. Furthermore, we can
also perform subtraction, multiplication, and division operation to use the binary operator
for various calculations.
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1.What is the difference between binary operator overloading with member
function and binary operator overloading with friend function in C++?State
output of the following code:
#include <iostream.h>
class Distance {
private:
int feet;
inches;
public:
// required constructors Distance() {
feet= 0;
inches= 0;
Distance(int f, inti)
{
feet= f;
inches= i;
}
void displayDistance() {
cout << "F: "<<feet<<" I:"<< inches <<endl;
void display()
{
cout <<value<< endl;
}
};
void main() {
overloading objl, obj2, result;
int a, b;
cout << "Enter the value of Complex Numbers a,b:";
cin >> a>>b;
objl.setValue(a);
obj2.setValue(b);
result= objl + obj2;
cout << "Input Values:\n";
objl.display();
obj2.display();
cout << "Result:";
result.display();
getch();
}
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
………………………………………………………………………………………………
..……………………………………………………………………………………………
..………………………………………………………………………………………………
XIII Conclusion
…………………………………………………………………………………………………
…………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or
attach more pages if needed.)
void get_data(){
cout << "Enter the value of Complex Numbers a, b: ";
cin >> a >> b;
}
void display(){
cout << a << "+" << b << "i" << "\n";
}
};
int main()
{
complex obj1, obj2, result, result1;
obj1.get_data();
obj2.get_data();
obj1.display();
obj2.display();
result.display();
result1.display();
return 0;
}
1. https://www.javatpoint.com/binary-operator-overloading-in-cpp
2. https://www.tutorialride.com/cpp-operator-overloading-
programs/demonstrating-operator-overloading-by-using-friend-function.htm
3. https://www.tutorialride.com/cpp-operator-overloading-
programs/overload- arithmetic-insertion-and-extraction-
operators.htm
4. https://www.tutorialride.com/cpp-operator-overloading-
programs/compare-perform-arithmetic-operations-on-two-
fractions.htm
5. http://www.includehelp.com/cpp-programs/cpp-program-to-
add-two- objects-using-binary-plus-operator-
overloading.aspx
I Practical Significance:
The concept of virtual function helps to learn the concept of run time
polymorphism in C++.
int main()
{
base* bptr;
derived d;
bptr = &d;
// Virtual function, binded at runtime
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
Maharashtra State Board of Technology (K Scheme) 123
Object Oriented Programming Using C++ (313304)
return 0;
}
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
IX Exercise:
1.What is function overriding?
2. Write output for following code:
#include<iostream.h>
class A
{
public:
virtual void fun()
{
cout << "\n A::fun() called ";
}
};
class B : public A
{
public:
void fun()
{
cout << "\n B::fun() called ";
}
};
class C : public B
{
public:
void fun()
{
cout << "\n C::fun() called ";
}
};
1. A
2. A and B
3. A, B, and C
4. D
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
………………………………………………………………………………………………………
……………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
Maharashtra State Board of Technology (K Scheme) 125
Object Oriented Programming Using C++ (313304)
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
1. Define a class parent in which use read function, define another class child use same
read function. Display the data of both the read function on output screen using virtual
function.
class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
return 0;
}
b. #include <iostream>
using namespace std;
class Base {
Maharashtra State Board of Technology (K Scheme) 126
Object Oriented Programming Using C++ (313304)
public:
virtual void display()
{
cout << "Base class function";
}
};
int main()
{
Child C;
C.display();
return 0;
}
1. https://www.geeksforgeeks.org/virtual-function-cpp/
2. https://www.geeksforgeeks.org/virtual-functions-in-derived-classes-in-cpp/?ref=lbp
3. https://www.programiz.com/cpp-programming/virtual-functions
4. https://www.includehelp.com/cpp-programming/virtual-function-aptitude-questions-
and-answers.aspx
I Practical Significance:
The concept of pure virtual function helps to learn the concept of run time
polymorphism in C++.
A pure virtual function (or abstract function) in C++ is a virtual function for which
we can have an implementation, But we must override that function in the derived class,
otherwise, the derived class will also become an abstract class. A pure virtual function is
declared by assigning 0 in the declaration.
// An abstract class
class Test {
// Data members of class
public:
Maharashtra State Board of Technology (K Scheme) 129
Object Oriented Programming Using C++ (313304)
// Pure Virtual Function
virtual void show() = 0;
/* Other members */
};
A pure virtual function is implemented by classes that are derived from an Abstract class.
VII Resources Required
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1.What is pure virtual function?
2. Write output for following code:
#include <iostream>
using namespace std;
class Base {
// private member variable
int x;
public:
// pure virtual function
virtual void fun() = 0;
public:
// implementation of the pure virtual function
void fun() { cout << "fun() called"; }
};
Maharashtra State Board of Technology (K Scheme) 130
Object Oriented Programming Using C++ (313304)
int main(void)
{
// creating an object of Derived class
Derived d;
return 0;
}
3. #include <iostream>
using namespace std;
class Base {
public:
virtual void show() = 0;
};
int main(void)
{
Base* bp = new Derived();
bp->show();
return 0;
}
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
………………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
1. Write a program which show the use of Abstract class.
class D:public B {
public:
void s() {
cout << "Virtual Function in Derived class\n";
}
};
int main() {
B *b;
D dobj;
b = &dobj;
b->s();
}
b)#include <iostream.h>
using namespace std;
class Test {
Maharashtra State Board of Technology (K Scheme) 132
Object Oriented Programming Using C++ (313304)
int x;
public:
virtual void show() = 0;
int getX() { return x; }
};
int main(void)
{
Test t;
return 0;
}
in-cplusplus
2. https://www.geeksforgeeks.org/pure-virtual-
functions-and-abstract-classes/
3. https://ww.geeksforgeeks.org/c-interview-questions-on-virtual-function-and-
abstract-class/
• Constructor
• Open()
I Practical Significance:
Files store the output of a program and help to perform various operations on it.
Files help store these data permanently on a storage device.
II Industry/Employer Expected Outcome(s)
Virtual base classes used to prevent multiple instances of a given class from
appearing in an inheritance hierarchy when using multiple inheritances.
1. Write/ Compile/ debug/ Execute simple C++ program using read and
write data from a file.
Opening a File:
1. The first operation generally performed on an object of one
of these classes to use a file is the procedure known as to
opening a file.
2. An open file is represented within a program by a stream and
any input or output task performed on this stream will be
applied to the physical file associated with it.
3. The syntax of opening a file in C++ is:
open (filename, mode);
4. There are some mode flags used for file
opening. ios::app: append
mode
ios::ate: open a file in this mode for
output and read/write controlling to the
end of the file 10s::m: open file in
this mode for reading ios::out: open
file in this mode for writing
ios::trunk: when any file already exists, its
contents will be truncated before file opening
Closing a File:
1. When any C++ program terminates, it automatically
flushes out all the streams releases all the allocated
memory and closes all the opened files.
2. But it is good to use the close() function to close the file
related streams and it is a member of ifsream, ofstream
and fstream objects.
3. The structure of using this function is:
void
close(); General functions used for
file handling:
1. open(): To create a file
2. close(): To close an existing file
3. get(): to read a single character from the file
4. put(): to write a single character in the file
5. read(): to read data from a file
6. write(): to write data into a file
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
IX Exercise:
2.Write a program in C++ in which open a file read and write mode ad display
the content on
3. output screen using function open()
4.Write a program in C++ in which open a file read and write mode ad display the
content
on output screen using constructor.
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
……………………………………………………………………………………………………
Maharashtra State Board of Technology (K Scheme) 137
Object Oriented Programming Using C++ (313304)
…..………………………………………………………………………………………………
…..………………………………………………………………………………………………
XIII Conclusion
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or
attach more pages if needed.)
2. Which function is used to position back from the end of file object?
a) seekg () b) seekp()
c) both seekg() & seekp() d) none of the mentioned
3. Write a C++ program to Read and Display File's Content.
4. Write a C++ program to List Files in Current Directory.
5.What is the return type open() method?
a)int
b)char
c)bool
d) float
a)#include<iostream.h>
#include<fstream.h>
#include<cctype.h>
int main ()
{
ifstream ifile; ifile.open ("text.txt");
char last; ifile.ignore (256, ' '); last=
ifile.get();
cout << "Your initial is"<< last<< '\n';
ifile.close();
return 0
Maharashtra State Board of Technology (K Scheme) 138
Object Oriented Programming Using C++ (313304)
}
b) #include <iostream>
#include <fstream>
using namespace std;
int main ()
{
int length;
char * buffer;
ifstream is;
is.open ("sample.txt", ios :: binary );
is.seekg (0, ios :: end);
length = is.tellg();
is.seekg (0, ios :: beg);
buffer = new char [length];
is.read (buffer, length);
is.close();
cout.write (buffer, length);
delete[] buffer;
return 0;
}
1. https://www.geeksforgeeks.org/file-handling-c-
2. https://www.javatpoint.com/cpp-files-and-streams
3. https://www.tutorialspoint.com/cplusplus/cpp_files_streams.h
Practical No.24: Write programs to copy the contents of one file into another file
using formatted input/output function.
I Practical Significance:
To copy the file using C++, we read the contents of the source file and write it into the
destination file.
Copying is a file operation that creates a new file which has the same content as an
existing file
Implement copy the contents of one file into another file using formatted input/output
Function in C++ program.
Write/ Compile/ debug/ Execute simple C++ program to copy the contents of one
file into another file using formatted input/output function.
C++ helps you to format the I/O operations like determining the number of digits to be displayed
after the decimal point, specifying number base etc.
Example:
• If we want to add + sign as the prefix of out output, we can use the formatting to do so:
• stream.setf(ios::showpos)
If input=100, output will be +100
• If we want to add trailing zeros in out output to be shown when needed using the formatting:
• stream.setf(ios::showpoint)
If input=100.0, output will be 100.000
To copy the text/contents of one file to another file, we should know the basics of reading and
writing a text file in C++. To copy the file using C++, we read the contents of the source file and
write it into the destination file.
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1. Write programs to copy the contents of one file into another file using formatted
input/output function
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XII Result(s)
…………………………………………………………………………………………………
..………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………
…………………………………………………………………………………………………
…………………………………………………………………………………………………
XIV Practical Related Questions
Note: Below given are few sample questions for reference. Teacher
must design more such questions so as to ensure the achievement of
identified CO.
(Note: for all relevant programming exercise use blank pages provided or
attach more pages if needed.)
1. Write a C++ program to Read Content From One File and Write it Into
Another File.
2. Write a C++ Program to Copy the Contents of One File Into Another File.
3. Complete the following table:
State output
1. https://www.geeksforgeeks.org/cpp-program-to-copy-one-file-into-another-file/
2. https://www.tutorialspoint.com/c-program-to-copy-the-contents-of-one-file-to-another
file
Practical No.25: Write file programs to implement sequential input and output operations
on file.
I Practical Significance:
Input and output operations are performed using streams, which are sequences of bytes
that can be read from or written to.
File can only be accessed sequentially from the beginning to the end.
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
…………………………………………………………………………………………………
..…………………………………………………………………………………………………
XIII Conclusion
…………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
a. Write a C++ program to Read Content from One File and Write it Into
another File.
b. Write a C++ Program to Copy the Contents of One File Into Another File.
a) #include<iostream>
#include <fstream>using namespace std;
int main()
{
int length;
char * buffer ;
ifstream is;is.open ("sample.txt",
ios:: binary );
is.seekg (0, ios:: end);
length= is.tellg();
is.seekg (0, ios:: beg);
buffer= new char [length];
is.read(buffer,length);is.close();
cout.write(buffer,length);
delete[] buffer ;
return 0;
}
a)This is sample
b) sample
c) Error
d) Runtime error
b) #include <iostream>
#include <fstream>
int main() {
// Writing data sequentially
std::ofstream outfile("data.txt");
if (outfile.is_open()) {
outfile << "Record 1\n";
outfile << "Record 2\n";
outfile << "Record 3\n";
outfile.close();
}
1. https://codescracker.com/cpp/cpp-sequential-io-with-files.htm
2. https://programmingknow.com/cpp-sequential-input-output/
Files.
I Practical Significance:
Binary file is a file with data stored in raw format, the way it is stored in memory.
Binary files can be used to store any data. The data inside a binary file is stored as raw
bytes, which is not human readable.
1. Write/ Compile/ debug/ Execute simple C++ program to perform input/output operations on
Binary Files.
Binary File
Binary file is a file with data stored in raw format, the way it is stored in memory.
For example, numbers are stored in binary in memory. They are not converted to text (ASCII
characters) when writing to binary file.
The data in binary format is not human readable and cannot be read or modified using text editors.
See following example to understand this.
Consider integer value 65536. When read from keyboard, it is entered using keys ‘6’, ‘5’, ‘5’, ‘3’,
‘6’ as ASCII characters. But in memory, data is stored in binary format as 0x’0001FFFF’.
Integer 65536 stored as text (using 5 ASCII characters)
00
ASCII in 00 00000 00000 00000 00000
Binary 01 101 101 011 110
10
ASCII in
06 05 05 03 06
Hexa
Integer 65536 stored as binary in memory (assuming long int, using 4 bytes):
In Hexa 00 01 FF FF
When writing the output on screen, it requires converting data stored in memory to text.
Thus, 0x’0001FFFF’ is converted to 5 characters ‘6’, ‘5’, ‘5’, ‘3’, ‘6’.
Thus, working with text files requires conversion from binary to text or vice versa.
When data is stored in binary file, it does not require such conversion. Integer 65536 is stored as
0x’0001FFFF’ using 4 bytes without any conversion.
Working with files in C++ requires the use of file-oriented streams based on classes:
ifstream, ofstream and fstream.
Opening binary file is similar to opening text files, but requires specifying ios::binary as additional
open mode. A file stream object can be opened in one of two ways.
First, supply a file name along with an i/o mode parameter to the constructor when declaring an object:
Syntax: FileStream FileObject (const char *filename[, int mode][, int prot]);
Syntax of open(): void open(const char *filename[, int mode][, int prot]);
Either approach will work equally well with ifstream, ofstream or fstream object. In the syntax given
here, [] indicates that the mode and prot arguments are optional. Default mode is ios::in for ifstream,
ios::out for ofstream and ios::in | ios::out for fstream.
For binary I/O, opening with mode flag ios::binary indicate to suppress formatting and conversion.
Note: When working with text files, one may omit the second parameter (the i/o mode parameter) to
use the default mode. However, in order to manipulate binary files, it is necessary to specify the i/o
mode also along with ios::binary mode.
Method write() can be used to write data to binary file associated with ofstrem or fstrem object.
The write() method causes specified size of bytes to be written from the given memory location buf
to binary
file on given stream and moves the file pointer size bytes ahead.
Following example writes two numbers in file. First is of type int, and second is of type double. Note
that it requires typecasting to (char *) as per syntax. To know the size of an item to be written, one
may use sizeof() operator.
int i = 1234;
double d = 12.34;
ofstream fout(“data.bin”, ios::out | ios::binary);
fout.write((char *)&i, sizeof(int));
fout.write((char *)&d, sizeof(double));
Use read() method to read from a binary file associated with fstream or ifstream object.
Function read() extracts a given number of bytes from the specified stream and store it into the
memory pointed to by the first parameter which is a C-type array of characters.
Following example reads two numbers (int and double) from binary file. Note typecasting (char *)
used to convert address of int or double to pointer to char.
Example code:
int i;
double d;
ifstream fin(“data.bin”, ios::in | ios::binary);
fin.read((char *)&i, sizeof(int));
fin.read((char *)&d, sizeof(double));
Sr. Name
Resource Specification Quantity Remarks
No
1 Computer Any desktop or laptop computer with One computer system for
System
basic configuration each student
2 Operating Windows /LINUX One for each computer
system system
3 Software Turbo C++ Version 3.0 or any One for each computer
other system
IX Exercise:
1. Write program to copy contents of one file to another file using get () and put
() methods.
X C++ code:
Write “C++” Code for above exercise on the blank pages attached at the end of practical.
XI Resources Used
XII Result(s)
………………………………………………………………………………………………………
………………………………………………………………………………………………………
XIII Conclusion
………………………………………………………………………………………………………
………………………………………………………………………………………………………
(Note: for all relevant programming exercise use blank pages provided or attach
more pages if needed.)
1 Write C++ Program to write and read objects in binary file using write ()
and read () methods.
3. Write a C++ program to copy entire content of one binary file at a time to another
file using read () and write ()
a)#include <iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
fin.open(“file1.pdf”, ios::in | ios::binary);
ifstream fout;
fout.open(“file2.pdf”, ios::out | ios::binary);
if (! (fin.is_open() && fout.is_open()))
{ cout << “Error opening file…”,
exit(1);
}
char ch;
while(!fin.eof())
{ ch = fin.get(); fout.put(ch); }
fin.close();
fout.close();
return 0;
}
b)#include<iostream.h>
#include<stdlib.h>
#include <fstream.h>
class Student
{
private:
int number;
char name[50];
float gpa;
public:
Student(int n, const char *s, float g);
void save(ofstream& of);
void load(ifstream& inf);
};
main()
{
Student me(11321, "Myself", 4.3);
ofstream myfile;
myfile.open("silly.dat", ios::binary | ios::out);
me.save(myfile);
myfile.close();
return(0);
}
…………………………………………………………………………………………………………………
…………………………………………………………………………………………………………………
…………………………………………………………………………………………………………………
…………………………………………………………………………………………………………………
…………………………………………………………………………………………………………………
…………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
1. https://www.geeksforgeeks.org/file-handling-c-classes/
2. https://ebooks.inflibnet.ac.in/itp1/chapter/binary-files-in-c/