OOP Lab LabModule
OOP Lab LabModule
0
Lab # Contents Pg #
1 Revision of Programming Fundamentals Concept 2
2 Objects And Classes 10
3 Constructors And Destructor of Class 16
4 Member Functions Outside the Class 25
5 Static Class Data 31
6 Arrow Operator and Inheritance 34
7 Modes Of Inheritance 38
8 Types Of Inheritance 42
9 Polymorphism 50
10 Late Binding 53
11 Virtual Classes & Friend Functions 58
12 Static Functions 63
13 Operators And Static Binding (Operator Overloading) 66
14 Overloading Binary Operators & File Handling 74
1
LAB 1: Revision of Programming Fundamentals Concept
Objective:
The objective of this exercise is to revise concepts of Functions, Structures and
Pointers.
Introduction:
Pointers:
A pointer is a variable that is used to store a memory address. The reference
operator(&) is used to access the memory address of a variable and store it in a
pointer. The dereference operator(*) is used to access the value of the variable
whose address is stored in pointer.
Syntax:
Datatype *variable_name;
Functions:
A function is a named block of code that performs some action. The statements
written in a function are executed when it is called by its name.
There are two types of function:
User-defined Function
Built-in Function
Built-in Function:
A type of function that is available as a part of language is known as built-in
function or library function. These are ready made function stored in different
header files.
User-defined Function:
A type of function written by programmer is known as user-defined function.
User-defined function has a unique name.
Function Declaration
Function Definition
Function Call
2
Function Declaration:
Function declaration is a model of a function. It is also called function prototype.
It provides information to compiler about the structure of the function to be used
in program.
Syntax
Return-type Function-name (parameters);
Function Definition:
A set of statements that explains what a function does is called function
definition. The function definition can be written at the following place:
Before main() function
After main() function
In a separate file
The function definition consists of two parts:
1. Function Header
The first line of function definition is known as function header. It is also
called function declarator. It is similar to function prototype.
2. Function Body
The set of statements which are executed inside the function is known as
function body. The body of function appears after function declarator and the
statements are written in curly braces {}.
Syntax:
Return-type Function-name (parameters)
{
statement 1;
statement 2;
---
---
---
3
statement N;
}
Function Call
The statements that activates a function is known as function call. A
function is called with its name. Function name is followed by necessary
parameters in parentheses. If there are many parameters, these are separated by
commas. If there is no parameter, empty parentheses are used.
Passing Parameters to Function
Parameters are the values that are provided to a function when the
function is called. The sequence and types of parameters in function call must be
similar to the sequence and types of parameters in function declaration.
Parameters in function call are called actual parameters
Parameters in function declaration are called formal parameters.
Pass by Value
A parameter passing mechanism in which the value of actual parameter is
copied to formal parameters of called function is known as pass by value.
Pass by Reference
A parameter passing mechanism in which the address of actual parameter
is passed to the called function is known as pass by reference. The formal
parameter is not created separately in the memory. In function definition,
Address operator “&” is placed on left side of formal parameters to create
reference with actual parameters.
Pass by Pointer
A parameter can be passed to function using pointers. The address of
actual parameter is passed to the formal parameter if the formal parameters are
defined as pointers. It s similar to a passing parameters to a function by reference.
Structure
4
A structure is a collection of multiple data types that can be referenced
with single name. The data items in a structure are called structure elements,
members or fields. A structure is declared by using the keyword struct followed
by the structure name.
Syntax
Struct Struct_Name
{
Data_Type1 Identifier1;
Data_Type2 Identifier2;
-
-
}
2. Write a program that inputs two numbers in main() function, passes these
numbers to a function. The function displays the maximum number.
Solution:
#include<iostream>
using namespace std;
void max(int a, int b)
{
If(a>b)
cout<<”Maximum Number is “<<a;
else
cout<<”Maximum Number is “<<b;
}
int main()
{
int x, y;
cout<<”Enter two numbers: “;
cin>>x>>y;
max(x, y);
return 0;
6
}
3. Write a program that inputs base and height of a triangle in main function and
passes them to a function. The function finds the area of triangle and returns
it to main function where it is displayed on the screen.
Area = 1/2(Base*Height)
Solution:
#include<iostream>
using namespace std;
float area(int b, int h)
{
float a;
a=0.5 * b * h;
return a;
}
int main()
{
int base, height;
float ar;
cout<<”Enter base: “;
cin>>base;
cout<<”Enter height: ”;
cin>>height;
ar = area(base, height);
cout<<”Area of triangle is “<<ar;
return 0;
}
7
4. Write a program that inputs two integers in main function and passes the
integers to a function by reference. The function swaps the values. The main()
function should display the values before and after swapping.
Solution:
#include<iostream>
using namespace std;
void swap(int &x, int &c)
{
int t;
t=x;
x=y;
y=t;
}
int main()
{
int a, b;
cout<<”Enter an integer: “;
cin>>a;
cout<<”Enter an integer: “;
cin>>b;
cout<<”Values before swapping:\n”;
cout<<”a = ”<<a<<endl;
cout<<”b = “<<b<<endl;
cout<<”Swapping the values…”<<endl;
swap(a, b);
8
cout<<”Values after swapping:\n”;
cout<<”a = “<<a<<endl;
cout<<”b = “<<b<<endl;
return 0;
}
5. Write a program that declares a structure to store day, month and year of
birth date. It inputs three values and displays date of birth in dd/mm/yy
format.
#include<iostream>
using namespace std;
struct birth
{
int day;
int month;
int year;
};
int main()
{
birth b;
cout<<”Enter day of birth: “;
cin>>b.day;
cout<<”Enter month of birth: “;
cin>>b.month;
cout<<”Enter year of birth: “;
cin>>b.year;
cout<<”\nYour date of birth is “<<b.day<<”/”<<b.month<<”/”<<b.year;
return 0;
}
9
LAB 2: Objects and Classes
Objective:
The objective of this lab is to practice the concepts of classes and
objects.
Introduction:
Object:
An object represents an entity in the real world such as a person,
thing or concept etc. An object is identified by its name. An object consists of the
following two things:
Properties: Properties are the characteristics of an object.
Functions: Functions are the action that can be performed by an object.
Classes:
A collection of objects with same properties and functions is known
as class. A class is used to define characteristics of the objects.
Syntax:
class identifier
{
body of the class
}
Body of class is data members and member functions which
represents properties and functions of objects respectively.
Access Specifiers:
The commands are used to specify the access level of class members
are known as access specifiers.
“private” access specifier
The private access specifier is used to restrict the use of class
member within the class. Any member of the class declared with private access
specifier can only be accessed within the class. It cannot be accessed from outside
the class. It is also the default access specifier.
10
“public” access specifier
The public access specifier is used to allow the user to access a class
member within the class as well as outside the class. Any member of the class
declared with public access specifier can be accessed from anywhere in the
program.
Objects
A class is simply a model or prototype for creating objects. It is like a
new data type that contains both data and functions. An object is created in the
same way as other variables are created.
Syntax
class_name object_name;
Calling members with Objects
An object of a particular class contains all data members as well as
member functions defined in that class.
Syntax
object_name.function();
11
LAB Task List
1. Write a program that declares a class with one integer data member and
two member functions in() and out() to input and output data in data
member.
#include<iostream>
using namespace std;
class Test
{
private:
int num;
public:
void in(){
cout<<”Enter a number: “;
cin>>num;
}
void out(){
cout<<”Number is “<<num;
}
};
int main()
{
Test obj;
obj.in();
obj.out();
return 0;
}
2. Write a class Marks with three data members to store three marks. Write
three member functions in() to input marks, sum() to calculate and return
the sum and avg() to calculate and return the average marks.
#include<iostream>
using namespace std;
class Marks
{
private:
int a, b, c;
12
public:
void in()
{
cout<<”Enter three marks: “;
cin>>a>>b>>c;
}
int sum()
{
return a+b+c;
}
float avg()
{
return (a+b+c)/3.0;
}
};
int main()
{
Marks m;
int s;
float a;
m.in();
s = m.sum();
a = m.avg();
cout<<”Sum = “<<s<<endl;
cout<<”Average = “<<a<<endl;
return 0;
}
3. Write a class Result that contains roll no, name and marks of three subjects.
The marks are stored in an array of integers. The class also contains the
following member functions:
The input() function is used to input the values in data members
The show() function is used to displays the value of data members
The total() function returns the total marks of a student
The avg() function returns the average marks of a student
13
The program should create an object of the class and call the member
functions.
#include<iostream>
using namespace std;
class Result
{
private:
int rno, marks[3];
char name[50];
public:
void input()
{
cout<<”Enter Roll No.: “;
cin>>rno;
cout<<”Enter name: “;
gets(name);
for(int i=0; i<3; i++)
{
cout<<”Enter marks[“<<i<<”]:”;
cin>>marks[i];
}
}
void show()
{
cout<<”Roll No = ”<<rno<<endl;
cout<<”Name = “<<name<<endl;
for(int i=0; i<3; i++)
cout<<”Marks[“<<i<<”]:”<<marks[i]<<endl;
}
int total()
{
int t = 0;
for(int i=0; i<3; i++)
t = t + marks[i];
return t;
14
}
float avg()
{
int t = 0;
for(int i=0; i<3; i++)
t = t + marks[i];
return t/3.0;
}
};
int main()
{
Result r;
r.input();
r.show();
cout<<”\nTotal marks = “<<r.total()<<endl;
cout<<”Average marks = ”<<r.avg()<<endl;
return 0;
}
15
LAB 3: Constructor and Destructor of Class
Objective:
The objective of this lab is to cover the concepts of constructor,
default constructor and parameterized constructor, copy constructor and
destructor.
Introduction:
Constructor:
A type of member function that is automatically executed when an
object of that class is created is known as constructor. The constructor has no
return type and has same name that of class name.
Syntax:
class Name{
public:
Name()
{
Constructor Body
}
}
It is also known as default constructor.
Parameterized Constructor:
The method of passing parameters to a constructor is same as
passing parameters to normal functions. The only difference is that the
parameters are passed to the constructor when the object is declared. The
parameters are written in parenthesis along with the object name in declaration
statement.
Syntax:
class class_name{
public:
class_name(parameters with data types)
{
Constructor Body
}
}
And syntax for calling parameterized constructor is following:
16
class_name object(paramenters);
Copy Constructor:
A copy constructor is a member function that initializes an object using
another object of the same class. In simple terms, a constructor which creates an
object by initializing it with an object of the same class, which has been created
previously is known as a copy constructor.
Syntax:
class_name(class_name &obj){
data_member = obj.data_member;
}
In main program
class_name object_name(object_two);
OR
class_name object_name = object_two;
Constructor Overloading:
The process of declaring multiple constructors with same name but
different parameters is known as constructor overloading. The constructor with
same name must differ in one of the following ways:
Number of parameters
Type of parameter
Sequence of parameters
Constructor Initializer List:
Initializer list is used to initialize data members. The syntax begins with a
colon(:) and then each variable along with its value separated by a comma. The
initializer list does not end in a semicolon.
Constructorname(datatype value1, datatype
value2):datamember(value1),datamember(value2)
{
17
Constructor Body
}
Destructor:
A type of member function that is automatically executed when an object
of that class is destroyed is known as destructor. The destructor has no return
type and its name is same as class name. The destructor cannot return any value.
It also cannot accept any parameters. The destructor name is preceded by tilde
sign ~.
Syntax:
~class_name()
{
destructor body
}
Objects as Function Parameters:
Objects can also be passed as parameters to member functions. The
method of passing objects to a function as parameters is same as passing other
simple variables.
Returning Objects from Member Functions:
The method of returning an object from member function is same as
returning a single variable. If a member function returns an object, its return type
should be the same as the type of object to be returned.
this Pointer
1. When variable name is same as member’s name
class Test
{
private:
int x;
public:
void setX (int x)
18
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
};
2. To return reference of the calling object
Test& Test::func ()
{
// Some processing
return *this;
}
24
LAB 4: Member Function Outside the Class
Objective:
Objective of this lab is to practice separate declaration and definition of
member functions. Moreover, we will see const keyword, accessors and utility
methods.
Introduction:
Member Function Defined Outside the Class
The member function of a class can be defined outside the class. The
declaration of member functions is specified within the class and function
definition is specified outside the class. The scope resolution operator :: is used in
function declaration if the function is defined outside the class.
Syntax
return_type class_name :: function_name(parameters)
{
function body
}
Accessor & Utility Function
Accessor function can read or display data. It does not contain any
statement to perform any operation that changes the value of data member.
Most common use of accessor function is to access private members of a class.
Whereas, A utility function is not part of a class's public interface; rather, it is a
private member function that supports the operation of the class's public
member functions.
Example:
class AreaOfCircle{
private:
float radius;
float getRadius(){
return radius; //accessor function
25
}
double getArea(){ //utility function
return 3.14*getRadius()*getRadius();
}
public:
AreaOfCircle(){
radius=0;
}
void inputRadius(){
cout<<"Enter Radius: ";
cin>>radius;
}
void printArea(){
cout<<"Area is "<<getArea()<<endl;
}
};
Cascaded Function Calls
C++ programming allows calling functions like this, when multiple functions
called using a single object name in a single statement, it is known as cascaded
function call in C++.
Example
class Demo {
public:
Demo FUN1()
{
cout << "\nFUN1 CALLED" << endl;
return *this;
}
Demo FUN2()
{
cout << "\nFUN2 CALLED" << endl;
return *this;
}
Demo FUN3()
{
26
cout << "\nFUN3 CALLED" << endl;
return *this;
}
};
In main program
main()
{
Demo ob;
ob.FUN1().FUN2().FUN3();
return 0;
}
27
LAB Task List
1. Write a class circle with one data member radius. Write three member
functions, get radius() to set radius value with parameter value, area() to
display radius and circum() to calculate and display circumference of circle.
#include<iostream>
using namespace std;
class circle
{
private:
float radius;
public:
void get_radius(float r);
void area();
void circum();
};
void circle::get_radius(float r){
radius = r;
}
void circle::area(){
cout<<”\nArea of circle: ”<< 3.14 * radius * radius;
}
void circum()
{
cout<<”\nCircumference of circle: “<< 2 * 3.14 * radius;
}
int main()
{
circle c1;
float rad;
cout<<”Enter radius: “;
cin>>rad;
c1.get_radius(rad);
c1.area();
c1.circum();
return 0;
28
}
2. Write a C++ program for a class Cuboid with 2 access modifiers “public and
private” in which the variables length, width, and height will be public and a
display message function will be public. Create 2 utility methods i.e.,
calculateVolume() and calculateArea(). Also, the display message function will
be within the class while both of the utility functions will be outside the class
using the :: operator.
#include <iostream>
using namespace std;
class Cuboid {
public:
int length;
int width;
int height;
// a public method to call both calculateArea and calculateVolume
functions
void display() {
cout << "\n\nCuboid Details\n";
cout << "Cuboid Length = " << length << "\n";
cout << "Cuboid Width = " << width << "\n";
cout << "Cuboid Height = " << height << "\n";
cout << "Area of cuboid = " << calculateArea() << "\n";
cout << "Volume of cuboid = " << calculateVolume() << "\n";
}
private:
//utility methods for calculating area
int calculateArea();
int calculateVolume();
};
int main() {
//creating objects of rectangle and cuboid
Cuboid cuboid;
//assigning values to cuboid
cuboid.length = 5;
cuboid.height = 7;
cuboid.width = 9;
//getting the result of area and volume of cuboid
cuboid.display();
return 0;
}
30
LAB 5: Static Class Data
Objective:
This lab’s objective is to practice static data members of classes.
Introduction:
31
Syntax
const Class-name object;
LAB Task List
1. Write a program that counts the number of objects created of a particular
class.
#include<iostream>
using namespace std;
class yahoo
{
private:
static int n;
public:
yahoo()
{
n++;
}
void show()
{
cout<<”You have created “<<n<<” objects so far.”<<endl;
}
};
int yahoo::n = 0;
int main()
{
yahoo x, y;
x.show();
yahoo z;
x.show();
return 0;
}
2. Write a program that creates three objects of class Student. Each object of
class must be assigned a unique roll number.
#include<iostream>
using namespace std;
class Student{
private:
static int r;
32
int rno, marks;
char name[50];
public:
Student()
{
r++;
rno = r;
}
void in()
{
cout<<”Enter name: “;
gets(name);
cout<<”Enter marks: “;
cin>>marks;
}
void show()
{
cout<<”Roll No: “<<rno<<endl;
cout<<”Name: “<<name<<endl;
cout<<”Marks: “<<marks<<endl;
}
};
int Student::r = 0;
int main()
{
Student s1, s2, s3;
s1.in();
s2.in();
s3.in();
s1.show();
s2.show();
s3.show();
return 0;
}
33
LAB 6: Arrow Operator and Inheritance
Objective:
This lab’s objective is to see the concepts of pointer objects and dynamic
memory allocation. Moreover, we will practice basics of inheritance as well.
Introduction:
Inheritance:
A programming technique that is used to reuse an existing class to build a
new class is known as inheritance. The new class inherits all the behavior of the
original class. The existing class that is reused to create a new class is known as
super class, base class or parent class. The new class that inherits the properties
and functions of an existing class is known as subclass, derived class or child class.
The inheritance relationship between the classes of a program is called a class
hierarchy.
Syntax:
class sub_class : specifier parent_class
{
Body of the class
}
Specifier indicates the type of inheritance. It can be private, public or
protected.
Protected Access Specifier
In inheritance, the private data members of a class are only accessible in
the class in which they are declared. The public data members are accessible from
anywhere in the program. The protected access specifier is different from private
and public access specifiers. It is specially used in inheritance. It allows a
protected data member to be accessed from all derived classes but not form
anywhere else in the program. It means that child class can access all protected
data members of its parent class.
34
Accessible from
Accessible from Accessible from
Access Specifier objects outside
own class derived class
class
public Yes Yes Yes
protected Yes Yes No
private Yes No No
35
gets(address);
}
void showinfo()
{
cout<<”\nYour personal information is as follows:\n”;
cout<<”Id = “<<id<<endl;
cout<<”Name = “<<name<<endl;
cout<<”Address = “<<address<<endl;
}
};
class Student : public Person
{
private:
int rno, marks;
public:
Student()
{
Person::Person();
rno = marks = 0;
}
void getedu()
{
cout<<”Enter your roll no: “;
cin>>rno;
cout<<”Enter your marks: “;
cin>>marks;
}
void showedu()
{
cout<<”\nYour educational information is as follows:\n”;
cout<<”Roll No = “<<rno<<endl;
cout<<”Marks = “<<marks<<endl;
}
};
int main()
36
{
Student s;
s.getinfo();
s.getedu();
s.showinfo();
s.showedu();
return 0;
}
37
LAB 7: Modes of Inheritance
Objective:
In this lab we’ll practice modes of inheritance and some related concepts.
Introduction:
Derived and Base Class Constructors:
In this case, the derived object "is-an" instance of the base class as well. So,
when a derived object is created, the constructors from the base and derived
classes will run. The order in which they run is important, too -- the base class
constructor runs first, then the derived.
Constructors with Parameters:
To trigger the execution of a constructor (with parameters) of the base
class, you specify the name of a constructor of the base class with the parameters
in the heading of the definition of the constructor of the derived class.
Constructor initializer list is used with the definition of derived class constructor
to call base class constructor with appropriate parameters.
Modes Of Inheritance:
In inheritance, we studied that an access specifier keyword is mentioned
while creating parent child relationship between two classes. As given below
class Child: memberAccessSpecifier Parent
That keyword defines that what mode of inheritance would be used.
1. If member access specifier is public—that is, the inheritance is public—
then:
The public members of A are public members of B. They can be
directly accessed in class B.
The protected members of A are protected members of B. They can
be directly accessed by the member functions (and friend functions)
of B.
The private members of A are hidden in B. They cannot be directly
accessed in B. They can be accessed by the member functions (and
friend functions) of B through the public or protected members of A.
38
2. If member access specifier is protected—that is, the inheritance is
protected—then:
The public members of A are protected members of B. They can be
accessed by the member functions (and friend functions) of B.
The protected members of A are protected members of B. They can
be accessed by the member functions (and friend functions) of B.
The private members of A are hidden in B. They cannot be directly
accessed in B. They can be accessed by the member functions (and
friend functions) of B through the public or protected members of A.
3. If member access specifier is public—that is, the inheritance is public—
then:
The public members of A are private members of B. They can be
accessed by the member functions (and friend functions) of B.
The protected members of A are private members of B. They can be
accessed by the member functions (and friend functions) of B.
The private members of A are hidden in B. They cannot be directly
accessed in B. They can be accessed by the member functions (and
friend functions) of B through the public or protected members of A.
41
LAB 8: Types of Inheritance
Objective:
This lab’s objective is to practice the concepts of types of inheritance which
are single inheritance, hierarchical inheritance, multiple inheritance and
multilevel inheritance.
Introduction:
Hierarchical Inheritance:
Hierarchical Inheritance in C++ refers to the type of inheritance that has a
hierarchical structure of classes. A single base class can have multiple derived
classes, and other subclasses can further inherit these derived classes, forming a
hierarchy of classes. The following diagram illustrates the structure of Hierarchical
Inheritance in C++.
Syntax:
class base_class
{
//data members
//member functions
};
class derived_class1 : public base_class
{
//data members
//member functions
};
class derived_class2 : public base_class
{
//data members
//member functions
};
Multilevel Inheritance:
A type of inheritance in which a class is derived from another derived class
is called multilevel inheritance. In multilevel inheritance, the members of parent
class are inherited to the child class and the members of child class are inherited
42
to the grand child class. In this way, the members of parent class and child class
are combined in grand child class.
Syntax:
class base_class
{
//data members
//member functions
};
class derived_class1 : public base_class
{
//data members
//member functions
};
class derived_class2 : public derived_class1
{
//data members
//member functions
};
Multiple Inheritance
A type of inheritance in which a derived class inherit multiple base classes is
known as multiple inheritance. In multiple inheritance, the derived class combines
the members of all base classes.
Syntax
class child_class : public parent class1, public parent_class2
{
body of the class
}
Ambiguity in Multiple Inheritance
An important issue is multiple inheritance is the issue of ambiguity. The
ambiguity is created in multiple inheritance if the names of functions are similar
in two or more parent classes. The compiler cannot determine which function to
execute when the object of derived class attempts to execute such function.
#include<iostream>
43
using namespace std;
class A
{
public:
void show()
{
cout<<”Class A”<<endl;
}
}
class B
{
public:
void show()
{
cout<<”Class A”<<endl;
}
}
class C: public A, public B{};
int main()
{
C obj;
obj.show();
return 0;
}
Here in main function, there will be an error for ambiguous function call. It
can be resolved by using scope resolution operator with appropriate class name
as mentioned in following example.
#include<iostream>
using namespace std;
class A
{
public:
void show()
{
cout<<”Class A”<<endl;
}
}
44
class B
{
public:
void show()
{
cout<<”Class A”<<endl;
}
}
class C: public A, public B{};
int main()
{
C obj;
obj.A::show();
obj.B::show();
return 0;
}
45
cin>>phonenumber;
}
string getphone(){
return phonenumber;
}
};
class NatPhone: public LocalPhone{
private:
string citycode;
public:
void setcitycode(){
cout<<"Enter city code: ";
cin>>citycode;
}
string getcitycode(){
return citycode;
}
};
class IntPhone: public NatPhone{
private:
string countrycode;
public:
void setcountrycode(){
cout<<"Enter country code: ";
cin>>countrycode;
}
string getcountrycode(){
return countrycode;
}
};
int main(){
int choice;
cout<<"Press key according to the following menu:\n";
cout<<"1. Local Phone\n2. National Phone\n3. International Phone\n";
cin>>choice;
46
switch(choice){
case 1:
{
LocalPhone obj;
obj.setphone();
cout<<"Phone Number is "<<obj.getphone()<<"."<<endl;
break;
}
case 2:
{
NatPhone obj;
obj.setcitycode();
obj.setphone();
cout<<"Phone Number is
"<<obj.getcitycode()<<"-"<<obj.getphone()<<"."<<endl;
break;
}
case 3:
{
IntPhone obj;
obj.setcountrycode();
obj.setcitycode();
obj.setphone();
cout<<"Phone Number is
"<<obj.getcountrycode()<<"-"<<obj.getcitycode()<<"-"<<obj.getphone()<<"."<
<endl;
break;
}
default:
{
cout<<"Invalid Choice!"<<endl;
break;
}
}
47
return 0;
}
2. Create a base class Vehicle that has a default constructor that prints
message “Your object is a vehicle.”. Create a two derived classes
PassengerVehicle and FreightVehicle having default constructors that print
messages “Your object is a passenger vehicle.” and “Your object is freight
vehicle.” respectively. For PassengerVehicle create a derived class Bus
having default constructor that prints message “Your object is a bus.”
Similarly create a derived class Truck having default constructor that prints
message “Your object is a truck.” In main program, create two objects for
Bus and Truck class respectively.
#include<iostream>
using namespace std;
class Vehicle{
public:
Vehicle(){
cout<<"Your object is vehicle."<<endl;
}
};
class FreightVehicle: Vehicle{
public:
FreightVehicle(){
cout<<"Your object is a freight vehicle."<<endl;
}
};
class PassengerVehicle: Vehicle{
public:
PassengerVehicle(){
cout<<"Your object is a passenger vehicle."<<endl;
}
};
class Truck: FreightVehicle{
public:
Truck(){
cout<<"Your object is a truck."<<endl;
48
}
};
class Bus: PassengerVehicle{
public:
Bus(){
cout<<"Your object is a bus."<<endl;
}
};
int main(){
Bus b;
Truck t;
return 0;
}
49
LAB 9: Polymorphism
Objective:
In this lab, we’ll practice the concepts of polymorphism and its types.
Introduction:
Polymorphism:
Polymorphism is one of the main features of object-oriented programming.
Polymorphism in C++ allows us to reuse code by creating one function that's
usable for multiple uses. We can also make operators polymorphic and use them
to add not only numbers but also combine strings.
Types of Polymorphism
There are following two types of polymorphism.
I. Compile Time Polymorphism.
II. Runtime Polymorphism.
I- Compile Time Polymorphism:
When the relationship between the definition of different functions and their
function calls, is determined during the compile-time, it is known as compile-time
polymorphism. This type of polymorphism is also known as static or early binding
polymorphism.
In compile time polymorphism we study following methods;
Function Overloading.
Operator overloading.
o Function Overloading
Function overloading is a feature of object-oriented programming where two or
more functions can have the same name but different parameters. When a
function name is overloaded with different jobs it is called Function Overloading.
In Function Overloading “Function” name should be the same and the arguments
should be different.
50
o Operator overloading
It's a type of polymorphism in which an operator is overloaded to give it the user-
defined meaning. C++ allows us to specify more than one definition for a function
name or an operator in the same scope, which is called function overloading and
operator overloading, respectively.
51
Arrow Operator:
For pointer objects, we use arrow operator with objects instead of dot
operator to access data members and member function. The arrow operator is
formed by using a minus sign, followed by the greater than symbol, as given
below.
prt_obj -> function();
ptr_obj -> variable;
53
keyboard for this). The second step, use arrow operator -> to access the member
function using the pointer to the object.
Virtual Member Functions Accessed with Pointers
Virtual functions should be accessed using pointer or reference of base class type
to achieve runtime polymorphism. The prototype of virtual functions should be
the same in the base as well as derived class. They are always defined in the base
class and overridden in a derived class.
Virtual Destructors
A virtual destructor is used to free up the memory space allocated by the derived
class object or instance while deleting instances of the derived class using a base
class pointer object.
Example:
#include <iostream>
using namespace std;
class Base
{
public:
virtual ~Base() = 0;
};
class Child : public Base
{
public:
~Child() {}
};
int main()
{
54
Base *b = new Child;
delete b;
return 0;
}
55
cout<<"The width is : "<<endl;
cin>>l;
cout<<"The area of rec is :";
f=k*l;
cout<<f;
cout<<endl;
}
};
class circle : public shape {
public:
int d,r,t;
void calculatearea()
{
cout<<"Enter radius : "<<endl;
cin>>r;
t=r*r*3.144;
cout<<"The radius is :"<<t<<endl;
}
};
int main ()
{
shape *s;
rec r;
circle c;
s=&r;
56
(*s).calculatearea();
s=&c;
(*s).calculatearea();
return 0;
}
57
LAB 11: Virtual Classes & Friend Functions
Objective
The objective of this lab is to practice the concepts of class hierarchy, multiple
inheritance and solve diamond problem.
Class hierarchy
A class hierarchy or inheritance tree in computer science is a classification of
object types, denoting objects as the instantiations of classes (class is like a
blueprint, the object is what is built from that blueprint) inter-relating the various
classes by relationships such as "inherits", "extends", "is an abstraction of", "an
interface definition".[1] In object-oriented programming, a class is a template that
defines the state and behavior common to objects of a certain kind. A class can be
defined in terms of other classes.
Multiple Inheritance
Multiple Inheritance is the concept of the Inheritance in C++ that allows a child
class to inherit properties or behavior from multiple base classes. Therefore, we
can say it is the process that enables a derived class to acquire member functions,
properties, characteristics from more than one base class.
Diamond head Problem with example of Virtual classes
The Diamond Problem occurs when a child class inherits from two parent classes
who both share a common grandparent class. This is illustrated in the diagram
below:
58
Here, we have a class Child inheriting from classes Father and Mother. These two
classes, in turn, inherit the class Person because both Father and Mother are
Person. As shown in the figure, class Child inherits the traits of class Person twice
—once from Father and again from Mother. This gives rise to ambiguity since the
compiler fails to understand which way to go. This scenario gives rise to a
diamond-shaped inheritance graph and is famously called “The Diamond
Problem.”
59
class Child : public Father, public Mother { //Child inherits Father and Mother
public:
Child(int x):Mother(x), Father(x) {
cout << "Child::Child(int) called" << endl;
}
};
int main() {
Child child(30);
}
Friend Function
A friend function in C++ is a function that is preceded by the keyword “friend”.
When the function is declared as a friend, then it can access the private and
protected data members of the class.
Syntax
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
Friend Class
A friend class can access private and protected members of other class in which it
is declared as friend. It is sometimes useful to allow a particular class to access
private members of other class. For example, a LinkedList class may be allowed to
access private members of Node
60
LAB TASK LIST
1. Create a class with 3 private members. Create its friend class with 3 member
function to access each private member separately. For first one, calculate
factorial. For second one, calculate sum of squares from one to that number.
For 3rd one, display its cube.
#include<iostream>
using namespace std;
class A{
int a = 5, b = 3, c = 4;
friend class B;
};
class B{
public:
A obj1;
int a(){
return obj1.a;
}
int b(){
return obj1.b;
}
int c(){
return obj1.c;
}
};
int factorial(){
61
B obj;
int s=1;
for(int i=1; i<=obj.a();i++){
s+= i*i;
}
return s;
}
int sumofsquare(){
B obj;
int s=0;
for(int i=1; i<=obj.b(); i++){
s+= i*i;
}
return s;
}
int cube(){
B obj;
return obj.c()*obj.c()*obj.c();
}
int main()
{
cout<<"Factorial of first Variable a :"<<factorial()<<endl;
cout<<"Sum of sqaure of Variable b is :"<<sumofsquare()<<endl;
cout<<"Cube of Third variable c is:"<<cube()<<endl;
}
62
LAB 12: Static Functions
Objective
The objective of this lab is to practice the concepts of static data members, static
functions and also to access static functions and calling member functions of a
class without any object.
Static Data Members
When a data member is declared as static , only one copy of the data is
maintained for all objects of the class. Static data members are not part of objects
of a given class type. As a result, the declaration of a static data member is not
considered a definition.
Static Functions
It is a member function that is used to access only static data members. It cannot
access non-static data members not even call non-static member functions. It can
be called even if no objects of the class exist.
Syntax
static <return_type> <function_name>(<arguments>){
//code
}
65
LAB 13: Operators and Static Binding
Objective
The objective of this lab is to practice the concepts of operators, types of
operators and operators loading.
Introduction
In programming, an operator is a symbol that operates on a value or a variable.
Operators are symbols that perform operations on variables and values. For
example, + is an operator used for addition, while - is an operator used for
subtraction.
Unary Operators
Unary operators are the operators that operate on a single operand to produce a
specific value.
Plus, Minus, Increment and decrement operators are example of unary operators.
Binary Operators
A binary operator is an operator that operates on two operands and manipulates
them to return a result. Operators are represented by special characters or by
keywords and provide an easy way to compare numerical values or character
strings.
Some common binary operators
Equal (==)
Not equal (!=)
Less than (<)
Greater than (>)
Greater than or equal to (>=)
Less than or equal to (<=)
Logical AND (&&)
Logical OR (||)
Plus (+)
Minus (-)
Multiplication (*)
66
Divide (/)
Relational Operators
A relational operator is used to check the relationship between two operands. For
example, // checks if a is greater than b a > b; Here, > is a relational operator.
== Is Equal
!= Not Equal To
> Greater Than
< Less Than
>= Greater Than or Equal To
<= Less Than or Equal To
Operator Overloading
Overloaded operators are functions with special names: the keyword "operator"
followed by the symbol for the operator being defined.
67
Multiple Overloading
You can redefine or overload the function of most built-in operators in C++. These
operators can be overloaded globally or on a class-by-class basis. Overloaded
operators are implemented as functions and can be member functions or global
functions.
Comparison Operators
Comparison operators are used to compare two values (or variables). This is
important in programming, because it helps us to find answers and make
decisions. The return value of a comparison is either 1 or 0, which means true (1)
or false (0). These values are known as Boolean values.
Some of the following comparison operators are
== Equal to
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
68
private:
int date, month, year;
public:
void input(){
char temp;
cout<<"Enter date in pattern (dd/mm/yyyy): ";
cin>>date>>temp>>month>>temp>>year;
}
void show(){
cout<<"Date is "<<date<<"/"<<month<<"/"<<year<<endl;
}
bool validate(){
if(((date<=30&&date>=1)&&(month==4||month==6||
month==9||month==11))||((month==2&&year
%4==0)&&(date<=29&&date>=1))||((month==2&&year%4!
=0)&&(date<=28&&date>=1))||((date<=31&&date>=1)&&(month==1||
month==3||month==5||month==7||month==8||month==10||month==12)))
return true;
else
cout<<"Invalid Entry!"<<endl;
return false;
}
void operator ++ (int){
if((month==4||month==6||month==9||month==11)&&(date==30)){
date = 1;
69
month++;
}
else if((date==31)&&(month==1||month==3||month==5||month==7||
month==8||month==10||month==12)){
date = 1;
if(month==12){
month = 1;
year++;
}
else{
month++;
}
}
else if((month==2)&&(year%4==0)&&(date==29)){
date = 1;
month++;
}
else if((month==2)&&(year%4!=0)&&(date==28)){
date = 1;
month++;
}
else{
date++;
}
}
70
void operator -- (int){
if((month==4||month==6||month==9||month==11)&&(date==1)){
date = 31;
month--;
}
else if((date==31)&&(month==1||month==5||month==7||month==8||
month==10||month==12)){
if(month==1){
month = 12;
year--;
date = 31;
}
else if(month==8){
month--;
date = 31;
}
else{
month--;
date=30;
}
}
else if((month==3)&&(year%4==0)&&(date==1)){
date = 29;
month--;
}
71
else if((month==3)&&(year%4!=0)&&(date==1)){
date = 29;
month--;
}
else{
date--;
}
}
};
int main()
{
DateClass obj;
char ch;
do{
cout<<"Press key accroding to following menu..."<<endl;
cout<<"Press 1 to enter date!\n";
cout<<"Press 2 to display the date!\n";
cout<<"Press 3 to increment!\n";
cout<<"Press 4 to decrement!\n";
cout<<"Press 'e' if you want to exit OR Press anyother key to
continue: ";
cin>>ch;
switch(ch){
case '1':
do{
72
obj.input();
}while(!(obj.validate()));
break;
case '2':
obj.show();
break;
case '3':
obj++;
break;
case '4':
obj--;
break;
}
}while(ch!='e');
return 0;
}
73
LAB 14: Overloading Binary Operators & File Handling
Objective
The objective of this is to practice the concepts of cascaded calls to functions,
operator overloading and file handling.
Cascaded calls to operator functions
When an object calls an operator function by passing an argument and the
returned value of the operator function calls the next operator function in the
same expression, it is called as cascading of operators.
File Handling
File handling in C++ is a mechanism to store the output of a program in a file and
help perform various operations on it. Files help store these data permanently on
a storage device. The term “Data” is commonly referred to as known facts or
information. In the present era, data plays a vital role.
Opening the File
To read or enter data to a file, we need to open it first. This can be performed
with the help of ‘ifstream’ for reading and ‘fstream’ or ‘ofstream’ for writing or
appending to the file. All these three objects have open() function pre-built in
them.
Syntax
open( FileName , Mode );
Writing data to File
Till now, we learned how to create the file using C++. Now, we will learn how to
write data to file which we created before. We will use fstream or ofstream object
to write data into the file and to do so; we will use stream insertion operator (<<)
along with the text enclosed within the double-quotes.
74
With the help of open() function, we will create a new file named ‘FileName’ and
then we will set the mode to ‘ios::out’ as we have to write the data to file.
Syntax
FileName<<"Insert the text here";
Reading Data from File
Getting the data from the file is an essential thing to perform because without
getting the data, we cannot perform any task. But don’t worry, C++ provides that
option too. We can perform the reading of data from a file with the CIN to get
data from the user, but then we use CIN to take inputs from the user’s standard
console. Here we will use fstream or ifstream.
Syntax
FileName>>Variable;
Infile
We can also use inFile to read from the file. Here, inFile >> S takes in the file
stream, which is your file data, and uses a space delimiter (breaks it up by
whitespace) and then puts the contents in the variable S.
Example
If we had a file that had the data:
“My Cat is Hungry”
and we used inFile >> S here, i.e.:
code:
ifstream inFile("file.txt")
string words;
while(inFile >> words) {
cout << words << endl;
}
75
Closing the File
Closing a file is a good practice, and it is must to close the file. Whenever the C++
program comes to an end, it clears the allocated memory, and it closes the file.
We can perform the task with the help of close() function.
Syntax
FileName.close();
Deleting Records
Following are the various steps to delete records;
Step 1:Opening the file from which the record is to be deleted in reading mode
here “he.dat”
Step 2: Opening the file to which the new content is to be written in writing mode
here “temp.dat”
Step 3:Reading the file and Comparing the record roll no with that to be deleted
Step 4: If during reading the roll number to be deleted exists then display it else
write the record in temp.dat
Step 5: Finally after reading the complete file delete the file “he.dat” and rename
the new file “temp.dat” with “he.dat”
Step 6: If in the file record exist then print the record and print record successfully
deleted
Step 7: If the roll number does not exists then print “record not found”.
76
Lab Task List
1. Write a program that reads the contents of country.txt and display on the
screen.
#include<fstream>
#include<iostream>
using namespace std;
class Country
{
private:
int id;
char name[50];
public:
void get()
{
cout<<”Enter country id: “;
cin>>id;
cout<<”Enter country name: “;
cin>>name;
}
};
int main()
{
Country cn;
Ifstream in(“c:\\country.txt”,ios::binary);
in.read((char*)&cn, sizeof(cn));
cn.show();
in.close();
}
77