Final Oop 1941060
Final Oop 1941060
Compiler used: We used the g++ compiler to compile the C++ program.
Theory:
The main purpose of C++ programming is to add object orientation to the C programming
language and classes are the central feature of C++ that supports object-oriented programming and
A class is used to specify the form of an object and it combines data representation and
methods for manipulating that data into one neat package. The data and functions within a class are
A class definition starts with the keyword class followed by the class name; and the class
body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon
or a list of declarations. For example, we defined the Box data type using the keyword class as
follows −
class Box {
public:
};
The keyword public determines the access attributes of the members of the class that
follows it. A public member can be accessed from outside the class anywhere within the scope of
the class object. You can also specify the members of a class as private or protected which we
A class provides the blueprints for objects, so basically an object is created from a class. We
declare objects of a class with exactly the same sort of declaration that we declare variables of
Both of the objects Box1 and Box2 will have their own copy of data members.
The public data members of objects of a class can be accessed using the direct member access
operator (.).
This program demonstrates how classes and its objects are created in program. Using
Pseudo Code:
1. Start.
3. Declare the private and public data members and 5 member functions.
statements.
object(“ .” operator)
8. Stop
Conclusion:
//PRN : 1941060
//S3 Batch
#include<iostream.h>
#include<process.h>
#include<conio.h>
class Arith
private:
int x,y;
public:
int add();
int sub();
int mul();
int div();
};
int Arith::add()
cin>>x;
cin>>y;
return(x+y);
int Arith::sub()
cin>>x;
cin>>y;
return(x-y);
}
int Arith::mul()
cin>>x;
cin>>y;
return(x*y);
int Arith::div()
cin>>x;
cin>>y;
return(x/y);
main()
Arith obj;
char ch;
clrscr();
while(1)
cout<<"a:Addition"<<endl;
cout<<"s:Subtraction"<<endl;
cout<<"m:Multiply"<<endl;
cout<<"d:Division"<<endl;
cout<<"e:exit"<<endl;
cin>>ch;
switch(ch)
case 'a':
int a=obj.add();
cout<<"Addtion Result="<<a<<endl;
break;
case 's':
int s=obj.sub();
cout<<"Subtract Result="<<s<<endl;
break;
case 'm':
int m=obj.mul();
cout<<"Multiply Result="<<m<<endl;
break;
case 'd':
int d=obj.div();
cout<<"Division Result="<<d<<endl;
break;
case 'e':
exit(0);
}
CO207U Object Oriented Programming Lab
Aim: Write a C++ program to calculate multiplication of two numbers; use parameterized and
default constructor.
Compiler used: We used the g++ compiler to compile the C++ program.
Theory:
In C++, constructor is a special method which is invoked automatically at the time of object
creation. It is used to initialize the data members of new object generally. The constructor in C++
has the same name as class or structureThere can be two types of constructors in C++.
● Default constructor
● Parameterized constructor
A class constructor is a special member function of a class that is executed whenever we create
new objects of that class. A constructor will have exact same name as the class and it does not have
any return type at all, not even void. Constructors can be very useful for setting initial values for
A constructor which has no argument is known as default constructor. It is invoked at the time of
creating object
For e.g.
class Line {
public:
private:
double length;
};
different values to distinct objects. Let's see the simple example of C++ Parameterized Constructor.
A Copy constructor is an overloaded constructor used to declare and initialize an object from
another object.
o Default Copy constructor: The compiler defines the default copy constructor. If the user
For e.g.
class A
// copyconstructor.
If we have to use multiple constructors in one program,we can use it in by overloading constructors
Fore.g
Consider a class Student
class student
.......
..........
Pseudo Code:
1. Start.
6. Stop
Conclusion:
I perform a program to calculate multiplication of two numbers; by using parameterized and default
constructor.
//PRN : 1941060
//S3 Batch
#include<iostream>
class multiplication
{
int a ,b ,mul ;
public:
multiplication()
cout<<”default constructor”<<endl;
multiplication(int p,int q)
a = p;
b =q;
mul = a*b;
void display()
cout<<a<<”*”<<b<<”=”<<mul<<endl;
};
int main()
multiplication m1 , m2(14,12);
m2. Display();
CO207U Object Oriented Programming Lab
Aim: Write a C++ program to calculate the area of a rectangle,triangle and circle using function
overloading
Compiler used: We used the g++ compiler to compile the C++ program.
Theory :
Function Overloading is defined as the process of having two or more functions with the
same name, but different in parameters is known as function overloading in C++. In function
overloading, the function is redefined by using either different types of arguments or a different
number of arguments. It is only through these differences compiler can differentiate between the
functions.
Function overloading is the ability to create multiple functions of the same name with
different parameters. When we call overloaded function ,it is called according to its parameter list.
Here in this program the overloaded functions are as follows.The advantage of Function
overloading is that it increases the readability of the program because you don't need to use
different
Pseudo code:
1. Start
5. Call function area 4 times through objects and display the result of calculation of area
6. Stop
Conclusion:
I perform practical to calculate the area of a rectangle,triangle and circle using function overloading
//PRN : 1941060
//S3 Batch
#include<iostream >
int area(int,int);
float area(float);
float area(float,float);
int main()
Int I ,b ;
float r, bs, h;
cin>>l>>b;
cin>>r;
cin>>bs>>h;
return(l*b);
float area(float r)
return(3.14*r*r);
return((bs*h)/2);
}
CO207U Object Oriented Programming Lab
Aim:-Create two classes DM and DB which stores the value of distances.Dm stores distances in
meters and centimeters and DB in feet and inches.Write c++ program that can read values for
the class object and add one object of DM with another object of DB.Use a friend function to
carry out the addition operation.The object that stores the result may be a DM object or DB
object,depending on the units in which the results are required.The display should in the form of
feet and inches or meters and centimetres depending on the object on display.
Compiler used: We used the g++ compiler to compile the C++ program.
Theory:-
Friend function:
If a function is defined as a friend function in C++, then the protected and private data of a class
can be accessed using the function.By using the keyword friend compiler knows the given
function is a friend function.For accessing the data, the declaration of a friend function should be
done inside the body of a class starting with the keyword friend. for e.g.
class class_name
};
In the above declaration, the friend function is preceded by the keyword friend. The
function can be defined anywhere in the program like a normal C++ function. The function
definition does not use either the keyword friend or scope resolution operator.
1. The function is not in the scope of the class to which it has been declared as a friend.
2. It cannot be called using the object as it is not in the scope of that class.
4. It cannot access the member names directly and has to use an object name and dot
Conversion Chart:-
millimete
r (mm))
centimeter
(cm)
meter
(m)
Pseudo code:-
1. Start
8. Define friend function add and convert centimeters,meters,feet and inches into meters
11. Stop
Conclusion:
I perform practical to Create two classes DM and DB which stores the value of distances.Dm stores
distances in meters and centimeters and DB in feet and inches.Write c++ program that can read
values for the class object and add one object of DM with another object of DB.Use a friend function
to carry out the addition operation.The object that stores the result may be a DM object or DB
object,depending on the units in which the results are required.The displayshould in the form of feet
and inches or meters and centimetres depending on the object on display.
//PRN : 1941060
//S3 Batch
#include<iostream>
class DB;
class DM
private:
int m;
double cm;
public:
void input()
cin>>m>>cm;
void show()
}
int getm()
return m;
double getcm()
return cm;
friend DM add(DM,DB);
};
class DB
private:
int ft;
double in;
public:
DB()
ft = in =0;
DB(DM dm)
double xin;
ft = xin/12;
in = xin - (ft*12);
void input()
{
cout<<"Enter distance in feet - inches : ";
cin>>ft>>in;
void show()
friend DM add(DM,DB);
};
DM a;
double cm,in,xcm,xin;
cm = mc.m*100 + mc.cm;
in = fi.ft*12 + fi.in;
xcm = cm + in*2.54;
xin = in + cm*0.394;
a.m = xcm/100;
return a;
int main()
DM a;
DB b;
a.input();
b.input();
DM c;
DB d;
c = add(a,b);
d = add(a,b);
c.show();
d.show();
return 0;
}
CO207U Object Oriented Programming Lab
Theory:
overloaded to provide the special meaning to the user-defined data type. Operator overloading is
used to overload or redefines most of the operators available in C++. It is used to perform the
operation on the user-defined data type. For example, C++ provides the ability to add the
variables of the user-defined data type that is applied to the built-in data types.The advantage of
● Sizeof
● member selector(.)
● ternary operator(?:)
for e.g.
● Except for the function call, operator, operator functions cannot have default arguments.
● Finally, these operators cannot be overloaded: scope resolution operator (::), conditional
● Except for the = operator, operator functions are inherited by any derived class.
● However, a derived class is free to overload any operator (including those overloaded by
0 1 1 2 3 5 8 13 21.....
The first and second term is 0 and 1 respectively and the subsequent term is the addition
By this method, we can print the series upto n terms (which is user’s choice)
5. Define unary operator overloading (++) to change the values of third, first and second.
9. Define i=2 and check i less than n, if true goto STEP 10 else STEP 12.
12.Stop.
Conclusion:
//PRN : 1941060
//S3 Batch
#include<iostream>
class Fibo {
private:
int a,b,c;
public:
Fibo ()
a=0;
b=1;
c=a+b;
void show()
cout<<c<<" ";
void operator++()
a=b;
b=c;
c=a+b;
};
int main()
int n,i;
Fibo f1;
for(i=0;i<n;i++)
f1.show();
++f1;
return 0;
}
CO207U Object Oriented Programming Lab
Compiler used: We used the g++ compiler to compile the C++ program.
Theory:
The binary operators take two arguments and following are the examples of Binary
operators. We can use binary operators very frequently like addition (+) operator, subtraction (-)
operator and division (/) operator.We can use a friend function with built-in type data as the
left-hand operand and an object as the right-hand operand.As a rule, in overloading binary
operators,
The compiler invokes an appropriate constructor, initializes an object with no name and
returns the contents for copying into an object.Such an object is called a temporary object and
goes out of space as soon as the contents are assigned to another object. For e.g.
return complex((x+c.x), (y+c.y)); where complex is a class ‘c’ is an object of type complex
For e.g.
Pseudo Code:
1. Start
3. Declare the variable and its member function accept() and display().
5. Define the friend function +() to add two complex numbers and return object as an
argument.
7. In main function call the accept function twice and after performing addition on complex
Conclusion:
//PRN : 1941060
//S3 Batch
#include<iostream>
class complex
private:
float a,b;
public:
a=x;
b=y;
void display()
cout<<a<<"+"<<b<<"i"<<endl;
};
complex c;
c.a=c1.a+c2.a;
c.b=c1.b+c2.b;
return c;
int main()
complex c1;
complex c2;
c1.accept(4.5,5.4);
c2.accept(6.2,2.1);
c1.display();
c2.display();
complex sum;
sum=c1+c2;
sum.display();
return 0;
}
CO207U Object Oriented Programming Lab
Compiler used: We used the g++ compiler to compile the C++ program.
Theory:
One use of dynamically allocated memory is to allocate memory of variable size which is
not possible with compiler allocated memory except variable length arrays.The most important
use is flexibility provided to programmers. We are free to allocate and deallocate memory
whenever we need and whenever we don’t need anymore. There are many cases where this
flexibility helps. Examples of such cases are Linked List, Tree, etc.
For normal variables like “int a”, “char str[10]”, etc, memory is automatically allocated
and deallocated. For dynamically allocated memory like “int *p = new int[10]”, it is
doesn’t deallocate memory, it causes a memory leak (memory is not deallocated until program
terminates).
C uses malloc() and calloc() function to allocate memory dynamically at run time and
uses free() function to free dynamically allocated memory. C++ supports these functions and
also has two operators new and delete that perform the task of allocating and freeing the memory
The new operator denotes a request for memory allocation on the Heap. If sufficient memory is
available, new operator initializes the memory and returns the address of the newly allocated and
Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data type
including array or any user defined data types including structure and class.
Example:
int *p = NULL;
p = new int; or
Initialize memory: We can also initialize the memory using new operator:
Example:
Allocate a block of memory: new operator is also used to allocate a block(an array) of memory
of type data-type.
Example:
Dynamically allocates memory for 10 integers continuously of type int and returns pointer to the
first element of the sequence, which is assigned to p(a pointer). p[0] refers to first element, p[1]
There is a difference between declaring a normal array and allocating a block of memory
using new. The most important difference is, normal arrays are deallocated by compiler (If array
is local, then deallocated when function returns or completes). However, dynamically allocated
arrays always remain there until either they are deallocated by the programmer or program
terminates.
If enough memory is not available in the heap to allocate, the new request indicates
failure by throwing an exception of type std::bad_alloc, unless “nothrow” is used with the new
operator, in which case it returns a NULL pointer (scroll to section “Exception handling of new
operator” in this article). Therefore, it may be a good idea to check for the pointer variable
Pseudo Code:
1. Start
3. Define member functions create() and insert() and max() function inside a class.
8. Call all functions in main function and print array along with maximum number.
9. Stop
Conclusion:
//PRN : 1941060
//S3 Batch
#include <iostream>
class dyanamic
{
int *p;
int n,temp,maximum;
public:
void create()
p= new int[10];
void insert()
cin>>n;
for(int i=0;i<n;i++)
cin>>p[i];
void max()
for(int i=0;i<n;i++)
if(p[i]>p[i+1])
temp=p[i];
p[i]=p[i+1];
p[i+1]=temp;
maximum=p[i+1];
}
cout<<"Maximum insert is "<<maximum<<endl;
~dyanamic()
delete []p;
};
int main()
dyanamic o;
o.create();
o.insert();
o.max();
return 0;
}
CO207U Object Oriented Programming Lab
Aim: Write a program to calculate the total mark of a student using the concept of virtual base
class
Compiler used: We used the g++ compiler to compile the C++ program.
Theory:
Virtual base classes are used in virtual inheritance in a way of preventing multiple
inheritances.
Consider the situation where we have one class A .This class is 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 1 below.
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
would be called? One inherited through B or the other inherited through C. This confuses
compiler and it displays error.To resolve this ambiguity when class A is inherited in both class B
Syntax 1:
{
};
Syntax 2:
};
Virtual can be written before or after the public. Now only one copy of data/function
member will be copied to class C and class B and class A becomes the virtual base class.
Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies that use
multiple inheritances. When a base class is specified as a virtual base, it can act as an indirect
base more than once without duplication of its data members. A single copy of its data members
Pseudo Code:
1. Start
2. Create one class “Student” and define member function as getrno() and putrno() i.e. for
3. Derive class “Test” along with its member functions getmarks() and purmarks() which is
for getting marks of students and displaying marks from “Student” and make “Student”
4. Again define class “Sports” with its member function getscore() and putscore() for
getting sports marks and displaying it and make “Student” class as a virtual base class for
“Sports” class.
5. Create one more class “Result” with its member functions display() for calculating all
subject marks with sports marks. Define a multiple inheritance relationships between
classes ,such as
6. Call all functions from class Student ,Test,Sports in display() function of class
7. In main function,create an object of a class Result and pass roll number,subject marks
8. Stop
Conclusion:
I perform practical to calculate the total mark of a student using the concept of virtual base class
//PRN : 1941060
//S3 Batch
#include <iostream>
class Shape
public:
};
public:
void draw()
};
{
public:
void draw()
};
public:
void draw()
};
int main()
Shape S;
circle c;
square s;
triangle t;
S.draw();
Shape* p = &c;
p->draw();
p = &s;
p->draw();
p = &t;
p->draw();
}
CO207U Object Oriented Programming Lab
Compiler used: We used the g++ compiler to compile the C++ program.
Theory:
Manipulator Functions:
Manipulator functions are special stream functions that change certain characteristics of
the input and output. They change the format flags and values for a stream. The main advantage
of using manipulator functions is that they facilitate that formatting of input and output
streams.The following are the list of standard manipulator used in a C++ program. To carry out
the operations of these manipulator functions in a user program, the header file input and output
Predefined manipulators:Following are the standard manipulators normally used in the stream
classes:
1. endl
3. setbase
4. setw
5. setfill
6. setprecision
7. ends
8. ws
9. flush
10. setiosflags
11. resetiosflags
(a) Endl: The endl is an output manipulator to generate a carriage return or line feed character.
For example,
(1)
(2)
A program to display a message on two lines using the endl manipulator and the
#include <iostream.h>
My name is Komputer
The endl is the same as the non-graphic character to generate line feed (\n).
(b) Setbase(): The setbase() manipulator is used to convert the base of one numeric value into
In addition to the base conversion facilities such as to bases dec, hex and oct, the
setbase() manipulator is also used to define the base of the numeral value of a variable. The
prototype of setbase() manipulator is defined in the iomanip.h header file and it should be
include in user program. The hex,dec,oct manipulators change the base of inserted or extracted
integral values. The original default for stream input and output is dec.
PROGRAM
A program to show the base of a numeric value of a variable using hex, oct and dec
manipulator functions.
#include <iostream.h>
int value;
cout << “ Decimal base = “ << dec << value << endl;
cout << “ Hexadecimal base = “ << hex << value << endl;
cout << “ Octal base = “ << oct << value << endl;
Enter number
10
Decimal base = 10
Hexadecimal base = a
Octal base = 12
(c) Setw (): The setw ( ) stands for the set width. The setw ( ) manipulator is used to specify the
minimum number of character positions on the output field a variable will consume.The general
Which changes the field width to w, but only for the next insertion. The default field
width is 0.
For example,
Between the data variables in C++ space will not be inserted automatically by the
compiler. It is upto a programmer to introduce proper spaces among data while displaying onto
the screen.
PROGRAM
#include <iostream.h>
#include <iomanip.h>
int a,b;
a = 200;
b = 300;
cout << setw (5) << a << setw (5) << b << endl;
cout << setw (6) << a << setw (6) << b << endl;
cout << setw (7) << a << setw (7) << b << endl;
cout << setw (8) << a << setw (8) << b << endl;
200 300
200 300
200 300
200 300
(d) Setfill(): The setfill ( ) manipulator function is used to specify a different character to fill the
unused field width of the value.The general syntax of the setfill ( ) manipulator is
setfill( char f)
which changes the fill character to f. The default fill character is a space.
For example,
Conclusion:-
PROGRAM
A program to illustrate how a character is filled in filled in the unused field width of the
#include <iostream.h>
#include <iomanip.h>
int a,b;
a = 200;
b = 300;
cout << setw (5) << a << setw (5) << b << endl;
cout << setw (6) << a << setw (6) << b << endl;
cout << setw (7) << a << setw (7) << b << endl;
cout << setw (8) << a << setw (8) << b << endl;
***200***300
****200****300
*****200*****300
(e) Setprecision() :setprecision ( ) is used to control the number of digits of an output stream
display of a floating point value. The setprecision ( ) manipulator prototype is defined in the
Setprecision (int p)
Which sets the precision for floating point insertions to p. The default precision is 6
PROGRAM
A program to use the setprecision manipulator function while displaying a floating point
#include <iostream.h>
#include <iomanip.h>
float a,b,c;
a = 5;
b = 3;
c = a/b;
1.67
1.667
1.6667
1.66667
1.666667
(f) Ends: The ends is a manipulator used to attach a null terminating character (‘\0’) at the end
of a string. The ends manipulator takes no argument whenever it is invoked. This causes a null
PROGRAM
A program to show how a null character is inserted using ends manipulator while
#include <iostream.h>
#include <iomanip.h>
Void main ( )
“ number = 123 “
(g) Ws:The manipulator function ws stands for white space. It is used to ignore the leading white
/ /using ws manipulator
#include <iostream.h>
#include <iomanip.h>
Void main ( )
{
this is a text
(h) Flush: The flush member function is used to cause the stream associated with the output to
be completed emptied. This argument function takes no input prameters whenever it is invoked.
For input on the screen, this is not necessary as all output is flushed automatically. However, in
the case of a disk file begin copied to another, it has to flush the output buffer prior to rewinding
the output file for continued use. The function flush ( ) does not have anything to do with
#include <iostream.h>
#include <iomanip.h>
void main ( )
cout . flush ( ) ;
The hex, dec, oct, ws, endl, ends and flush manipulators are defined in stream.h. The
other manipulators are defined in iomanip.h which must be included in any program that
employs them.
(i) Setiosflags and Resetiosflags: The setiosflags manipulator function is used to control
different input and output settings. The I/O stream maintains a collection of flag bits.The
setiosflags manipulator performs the same function as the setf function.he flags represented by
the set bits in f are set.The general syntax of the setiosflags is,
setiosflags ( long h)
The restiosflags manipulator performs the same function as that of the resetf function.
The flags represented by the set bits in f are reset.The general syntax of the resetiosflags is a
follows,
Resetiosflags (long f)
PROGRAM
A program to demonstrate how setiosflags is set while displaying the base of a numeral.
#include <iostream.h>
#include <iomanip.h>
int value;
10
decimal = 10
hexadecimal = 0xa
octal = 012
#include <iostream>
#include <istream>
#include <sstream>
#include <string>
#include <iomanip>
int main()
string line;
// you can also write str>>ws , After printing the output it will automatically
// * Manipulator in <ios> *
double M = 100;
double N = 2001.5251;
double O = 201455.2646;
// formatting
// formatting
// formatting
return 0;
}
CO207U Object Oriented Programming Lab
Aim: Consider a class Number having a function to accept and print a roll_no., a class Marks
having function to accept and print marks of two subjects; and a class Student having function to
display total of two subjects. Write a C++ program to calculate total of 2 subjects for a student
Compiler used: We used the g++ compiler to compile the C++ program.
Theory:
Inheritance:
In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such a way, you can reuse, extend or modify the
attributes and behaviors which are defined in other class.In C++, the class which inherits the
members of another class is called derived class and the class whose members are inherited is
called base class. The derived class is the specialized class for the base class.you can reuse the
members of your parent class. So, there is no need to define the member again. So less code is
1. Single inheritance
2. Multiple inheritance
3. Hierarchical inheritance
4. Multilevel inheritance
5. Hybrid inheritance
When one class inherits another class which is further inherited by another class, it is
known as multi level inheritance in C++. Inheritance is transitive so the last derived class
acquires all the members of all its base classes
For example:
...........
};
...........
};
...........
};
Pseudo Code:
1. Start
2. Define a class “Number” which takes roll number in acceptt_rno() function and
3. Define class “Marks” which is derived from class number.Define member function
4. Define class “Student” which is again derived from class “Marks” having member
functions getdata() and dispaly_data() for calculating total marks and and display total
Number----------->Marks------------->Student
6. Stop
Conclusion:
I perform practical to Consider a class Number having a function to accept and print a
roll_no., a class Marks having function to accept and print marks of two subjects; and a class Student
having function to display total of two subjects. Write a C++ program to calculate total of 2 subjects
for a student using multilevel inheritance.
//PRN : 1941060
//S3 Batch
#include<iostream>
class number
public:
int rno;
void accept_rno()
cin>>rno;
void print_rno()
cout<<"Roll no :"<<rno<<endl;
};
public:
int mark1,mark2;
void accept_marks()
cin>>mark1>>mark2;
void print_marks()
};
public:
int total;
void getdata()
total=mark1+mark2;
void put_data()
cout<<endl;
cout<<"Roll no:"<<rno<<endl;
};
int main()
student s;
s.accept_rno();
s.print_rno();
s.accept_marks();
s.print_marks();
s.getdata();
s.put_data();
return 0;
}
CO207U Object Oriented Programming Lab
Compiler used: We used the g++ compiler to compile the C++ program.
Theory:
C++ Templates
A C++ template is a powerful feature added to C++. It allows you to define the generic classes
and generic functions and thus provides support for generic programming. Generic programming
is a technique where generic types are used as parameters in algorithms so that they can work for
● Function templates
● Class templates
Function Templates:
We can define a template for a function. For example, if we have an add() function, we can
create versions of the add function for adding the int, float or double type values.
Class Template:
We can define a template for a class. For example, a class template can be created for the array
class that can accept the array of various types such as int array, float array or double array.
Function Template
● Generic functions use the concept of a function template. Generic functions define a set
● The type of the data that the function will operate on depends on the type of the data
passed as a parameter.
● For example, Quick sorting algorithm is implemented using a generic function, it can be
● A Generic function is created by using the keyword template. The template defines what
2. {
3. // body of function.
4. }
Where Ttype: It is a placeholder name for a data type used by the function. It is used within the
function definition. It is only a placeholder that the compiler will automatically replace this
Class Template:
Class Template can also be defined similarly to the Function Template. When a class uses the
Syntax
1. template<class Ttype>
2. class class_name
3. {
4. .
5. .
6. }
Ttype is a placeholder name which will be determined when the class is instantiated. We can
define more than one generic data type using a comma-separated list. The Ttype can be used
1. class_name<type> ob;
Pseudo Code:
1. Start
e. {
f. mult[i][j]=0;
g. }
h.
m. {
o. }
q. Stop
Conclusion:
//PRN : 1941060
//S3 Batch
#include<iostream>
using namespace std;
template<class T>
class matrix
T m[r][c];
public:
void get_value()
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
cin>>m[i][j];
T p[r][c];
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
p[i][j]=m[i][j]+ob.m[i][j];
cout<<" "<<p[i][j]<<" ";
cout<<"\n";
T p[r][c];
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
p[i][j]=m[i][j]-ob.m[i][j];
cout<<"\n";
T p[r][c];
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
p[i][j]=0;
for(int k=0;k<c;k++)
{
p[i][j]+=(m[i][k] * ob.m[k][j]);
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
cout<<"\n";
void transpose()
T p[r][c];
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
p[j][i]=m[i][j];
}for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
{
cout<<" "<<p[i][j]<<" ";
cout<<"\n";
void display()
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
cout<<"\n";
cout<<"\n\n";
};
int main()
matrix<int> m1,m2;
int ch;
m1.get_value();
cout<<"\n Enter Elements of Matrix B\n";
m2.get_value();
while(1)
system("cls");
cout<<"\n 1. Sum";
cout<<"\n 2. Difference";
cout<<"\n 3. Product";
cout<<"\n 4. Transpose";
cout<<"\n 5. Display";
cout<<"\n 0. EXIT\n";
cin>>ch;
switch(ch)
m1 + m2;
break;
m1-m2;
break;
m1*m2;
break;
m1.display();
m1.transpose();
cout<<"\n MATRIX B\n";
m2.display();
m2.transpose();
break;
m1.display();
m2.display();
break;
case 0: exit(0);
system("pause");
};
}
CO207U Object Oriented Programming Lab
Aim:Generate record for student containing name, age, weight, height, blood group, phone
number and address. Print and store the record in the file.
Compiler used: We used the g++ compiler to compile the C++ program.
Theory:
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in
Now the first step to open the particular file for read or write operation. We can open file by
Opening a File
A file must be opened before you can read from it or write to it. Either ofstream or
fstream object may be used to open a file for writing. And ifstream object is used to open a file
for reading purpose only.Following is the standard syntax for open() function, which is a
Here, the first argument specifies the name and location of the file to be opened and the
second argument of the open() member function defines the mode in which the file should be
opened.
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.Following is the
standard syntax for close() function, which is a member of fstream, ifstream, and ofstream
objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using
the stream insertion operator (<<) just as you use that operator to output information to the
screen. The only difference is that you use an ofstream or fstream object instead of the cout
object.
Reading from a File
You read information from a file into your program using the stream extraction operator
(>>) just as you use that operator to input information from the keyboard. The only difference is
that you use an ifstream or fstream object instead of the cin object.
Both istream and ostream provide member functions for repositioning the file-position
pointer. These member functions are seekg ("seek get") for istream and seekp ("seek put") for
ostream.
The argument to seekg and seekp normally is a long integer. A second argument can be
specified to indicate the seek direction. The seek direction can be ios::beg (the default) for
positioning relative to the beginning of a stream, ios::cur for positioning relative to the current
Pseudo Code:
1. Start
3. In main() function
4. Stop
Conclusion:
I perform practical to Generate record for student containing name, age, weight, height , blood
group, phone number and address. Print and store the record in the file.
// S3 Batch
#include<iostream>
#include<fstream>
#include<string>
Class Student
String name;
Int age;
Float weight;
Float height;
String bloodGroph;
Int phone;
String address;
Public:
};
Cin.ignore();
// cin>>name;
Cin >>age;
Cout << “\nEnter Weight[KG] : “<<endl;
Cin.ignore();
Cin>>phone;
Cin.ignore();
Getline(cin, address);
Int main()
Student s[3];
Int n;
Cin>>n;
S[n];
Fstream file;
Int I;
Cout << “\nEnter “<<n<< “ students Details to the File :- “ << endl;
S[i].getData();
S[i].displayData();
File.close();
Return 0;
………………….
………………….
Output :-
Enter No of Students :
Enter Name :
Yash Patil
Enter Age :
20
Enter Weight[KG] :
61
Enter Height[Cms] :
178
Enter BloodGroup :
O+
9669297677
AGE : 20
WEIGHT : 61
HEIGHT: 178
Blood Group : O+
ADDRESS :indore
Aim: Create a simple "Shape" hierarchy. A base class called Shape and derived classes called
Circle, Square and Triangle. In the base class write a virtual function "draw" and override this in
derived classes.
Theory:
Hierarchical Inheritance:
In hierarchical inheritance several classes can be derived from a single base class.
Syntax:
class base-class-name
Data members
Member functions
};
Data members
Member functions
};
Data members
Member functions
};
Virtual Function:
Virtual means existing in appearance but not in reality. When virtual functions are used, a program
that appears to be calling a function of one class may in reality be calling a function of a different
class.Through this program we get the area of Circle ,Square and Triangle by using virtual member
function in base class.We have created the pointer of base class and stored the address of derived
Pseudo Code:.
11. Store address of derived class object to the base class pointer and call them.
12. Stop
Conclusion:
I perform practical tasks to Create a simple “Shape” hierarchy. A base class called Shape and derived
classes called Circle, Square and Triangle. In the base class write a virtual function “draw” and
override this in derived classes.
//PRN : 1941060
S3 Batch
#include<iostream>
class student
public:
int Roll_no;
void getrno()
cin>>Roll_no;
void putrno()
cout<<"Roll No :"<<Roll_no<<endl;
};
class test: virtual student
public:
int n,marks[10];
void getmark()
cin>>n;
cout<<"Enter marks:"<<endl;
for(int i=0;i<n;i++)
cin>>marks[i];
void putmark()
for(int i=0;i<n;i++)
cout<<i<<":"<<marks[i]<<endl;
};
public:
int m,score[10];
void getscore()
cout<<"Enter no of sports:"<<endl;
cin>>m;
cout<<"Enter marks:"<<endl;
for(int j=0;j<m;j++)
cin>>score[j];
void putscore ()
cout<<"scores:"<<endl;
cout<<j+1<<"."<<score [j]<<endl;
};
public:
int total_marks=0;
int total_score=0;
void total()
for(int k=0;k<n;k++)
total_marks=total_marks+marks[k];
total_score=total_score+score[i];
}
cout<<"total score ="<<total_score;
};
int main()
result r;
student s;
s.getrno();
s.putrno();
r.getmark();
r.putmark();
r.getscore();
r.putscore();
r.total();
return 0;
OUTPUT:-
Extra practicals experiments:file handling 2(grp B-5)
#include<iostream>
#include<fstream>
class Person
string name;
string occupation;
int age;
public:
void getdata()
cout<<"Name: ";
cin>>name;
cout<<"Age : ";
cin>>age;
cout<<"Occupation : ";
cin>>occupation;
void putdata()
string getName(){
return this->name;
}
}per1;
int main()
fstream fio("marks.dat",ios::app|ios::in|ios::out|ios::binary);
char ans='y';
while(ans=='y' || ans=='Y')
per1.getdata();
cin>>ans;
string name;
long pos;
char found='f';
cin>>name;
fio.seekg(0);
while(!fio.eof())
pos=fio.tellg();
if(per1.getName() == name)
{
per1.putdata();
fio.seekg(pos);
found='t';
break;
if(found=='f')
exit(1);
fio.close();
return 0;
OUTPUT :
Extra practicals experiments: calculating
perimeter(grpA_7)
#include <iostream>
class shape{
public:
int length;
int width;
};
public:
int Calculate_Area(){
return length*width;
};
public:
int Calculate_Perimeter(){
return 2*(length+width);
};
public:
void getDimention(){
void Calculate_Area_Perimeter(){
};
int main(){
Rectangle rectangle;
rectangle.getDimention();
return 0;
OUTPUT:-
44
Stack :
#include <iostream>
#include <stack>
int main() {
stack<int> st;
st.push(10);
st.push(20);
st.push(30);
st.push(40);
st.pop();
st.pop();
while (!st.empty()) {
cout<<" pop:";
st.pop();
cout<<"size :"<<st.size()<<endl;
OUTPUT :
Queue :
#include <iostream>
#include <cstdlib>
#define SIZE 10
class queue
int front; // front points to front element in the queue (if any)
public:
~queue(); // destructor
void dequeue();
int peek();
int size();
bool isEmpty();
bool isFull();
};
queue::queue(int size)
capacity = size;
front = 0;
rear = -1;
count = 0;
queue::~queue()
delete[] arr;
void queue::dequeue()
if (isEmpty())
exit(EXIT_FAILURE);
if (isFull())
exit(EXIT_FAILURE);
arr[rear] = item;
count++;
int queue::peek()
if (isEmpty())
exit(EXIT_FAILURE);
return arr[front];
}
// Utility function to return the size of the queue
int queue::size()
return count;
bool queue::isEmpty()
bool queue::isFull()
int main()
queue q(5);
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
cout << "Front element is: " << q.peek() << endl;
q.dequeue();
q.enqueue(4);
cout << "Queue size is " << q.size() << endl;
q.dequeue();
q.dequeue();
q.dequeue();
if (q.isEmpty())
else
return 0;
OUTPUT :
class Student{
string student_name;
int marks[3];
int total_marks;
float percentage;
public:
student_name = name;
for(int i=0;i<3;i++){
marks[i] = arr_marks[i];
total_marks = 0;
void Compute(){
total_marks = 0;
for(int i=0;i<3;i++){
percentage = total_marks/3;
void display(){
cout<<"Name : "<<student_name<<endl;
};
int main(){
int marks[3];
string name;
Student yash(name,marks);
yash.Compute();
yash.display();
return 0;
OUTPUT :
Extra Practice 2.Overloading = operator
#include <iostream>
class Point {
private:
int x;
int y;
public:
Point() {
x = 0;
y = 0;
Point(int a, int b) {
x = a;
y = b;
x = P.x;
y = P.y;
void showPoint() {
cout<<"Point is : "<<"("<<x<<","<<y<<")"<<endl;
}
};
int main() {
cout<<"First : ";
A.showPoint();
B.showPoint();
A.showPoint();
return 0;
OUTPUT :
Practice1_friend function n friend class
#include <iostream>
class Distance
{ private:
int meter;
public:
Distance()
meter=0;
void display()
//prototype
};
int main()
Distance d1;
d1.display();
cout<<endl<<endl;
d1.display();
return 0;
OUTPUT :
PROJECT REPORT
On
Submitted by:
1941060 Yash Patil
TEACHER NAME:
Shrutika Mahajan HOD: D.V. Chaudhary
TABLE OF CONTENTS
1 INTRODUCTION 1
2 Modules of Project 2
4 Snapshots Of Project 4
5 Conclusion 8
Appendix(Code) 9
REFERENCE 21
CHAPTER 1
INTRODUCTION
This project is for the practical implementation of Student Report card of any class. This program
follows modular approach for different task to make the code easy to understand. From this project
we can perform operations like create , view , edit , etc.
A C IDE
CHAPTER 2
MODULES OF PROJECT
1-Create Record(write())
In this module we can create record of any student by his unique roll no. and name with his\her
respective marks. This module also find grades and percentage automatically.
This module can show us all the students records present in the data file.
This module can show us the record of any individual student present in the data file via his/her roll
no.
4-Modifying Records(modify())
This module can modify all records of a student just by entering his/her existing roll no.
5-Deleting Records(del())
This module can delete all records of a student just by entering his/her existing roll no.
6-Class Result(classr())
This module can show us all the records of the whole class present in the data file .
Its can show us all the marks with names and grades.
CHAPTER 3
SNAPSHOTS OF PROJECTS
CONCLUSION
At the end it can be said that this project is highly efficient to store and process the marks by schools
and colleges.
Its Simple User Interface makes this project even more convenient in the real world to use.
It is based on the concepts of file Handling so we can easily transfer the file to any other pc at ease.
APPENDIX (CODE)
#include<conio.h>
#include<stdio.h>
#include<process.h>
#include<windows.h>
FILE *fptr;
struct student
int rollno;
char name[50];
int p,c,m,e,cs;
float per;
char grade;
}stud;
void write()
{
fptr=fopen("F:\\test\\student.dat","ab");
scanf("%d",&stud.rollno);
fflush(stdin);
gets(stud.name);
scanf("%d",&stud.p);
scanf("%d",&stud.c);
scanf("%d",&stud.m);
scanf("%d",&stud.e);
scanf("%d",&stud.cs);
stud.per=(float)(stud.p+stud.c+stud.m+stud.e+stud.cs)/5.0;
if(stud.per>=60)
stud.grade='A';
stud.grade='B';
stud.grade='C';
else
stud.grade='F';
fwrite(&stud,sizeof(stud),1,fptr);
fclose(fptr);
getch();
}
void display()
system("cls");
fptr=fopen("F:\\test\\student.dat","rb");
while((fread(&stud,sizeof(stud),1,fptr))>0)
printf("\n\n====================================\n");
getch();
fclose(fptr);
getch();
void display1(int n)
int flag=0;
fptr=fopen("F:\\test\\student.dat","rb");
while((fread(&stud,sizeof(stud),1,fptr))>0)
if(stud.rollno==n)
system("cls");
flag=1;
fclose(fptr);
if(flag==0)
getch();
void modify()
int no,found=0;
system("cls");
printf("\n\n\tTo Modify ");
scanf("%d",&no);
fptr=fopen("F:\\test\\student.dat","rb+");
if(stud.rollno==no)
scanf("%d",&stud.rollno);
fflush(stdin);
gets(stud.name);
scanf("%d",&stud.p);
scanf("%d",&stud.c);
scanf("%d",&stud.m);
scanf("%d",&stud.e);
printf(" marks in computer science out of 100 : ");
scanf("%d",&stud.cs);
stud.per=(stud.p+stud.c+stud.m+stud.e+stud.cs)/5.0;
if(stud.per>=60)
stud.grade='A';
stud.grade='B';
stud.grade='C';
else
stud.grade='F';
fseek(fptr,-(long)sizeof(stud),1);
fwrite(&stud,sizeof(stud),1,fptr);
found=1;
fclose(fptr);
if(found==0)
getch();
void del()
int no;
FILE *fptr2;
system("cls");
scanf("%d",&no);
fptr=fopen("F:\\test\\student.dat","rb");
fptr2=fopen("F:\\test\\Temp.dat","wb");
rewind(fptr);
while((fread(&stud,sizeof(stud),1,fptr))>0)
if(stud.rollno!=no)
fwrite(&stud,sizeof(stud),1,fptr2);
fclose(fptr2);
fclose(fptr);
remove("F:\\test\\student.dat");
rename("F:\\test\\Temp.dat","F:\\test\\student.dat");
getch();
void classr()
system("cls");
fptr=fopen("F:\\test\\student.dat","rb");
if(fptr==NULL)
getch();
exit(0);
printf("====================================================\n");
while((fread(&stud,sizeof(stud),1,fptr))>0)
fclose(fptr);
getch();
void result()
int ans,rno,a=1;
char ch;
system("cls");
scanf("%d",&ans);
switch(ans)
case 1 : classr();
break;
case 2 :
while(a==1){
system("cls");
scanf("%d",&rno);
display1(rno);
scanf("%d",&a);
break;
case 3: break;
default: printf("\a");
void firstpage()
system("cls");
getch();
void entry()
char ch;
system("cls");
printf("6.Main Menu\n");
ch=getche();
switch(ch)
write();
break;
case '3': {
int num;
system("cls");
scanf("%d",&num);
display1(num);
break;
void main()
char ch;
firstpage();
while(1)
system("cls");
ch=getche();
switch(ch)
{
case '1': system("cls");
result();
break;
break;
case '3':exit(0);
REFERENCE
3- https://www.geeksforgeeks.org/basics-file-handling-c/