0% found this document useful (0 votes)
12 views

OOP LAB Manual

The document discusses object oriented programming concepts like classes, objects, inheritance, polymorphism and strings. It contains details about arrays, classes, access specifiers, inheritance types and polymorphism types with examples. The document is intended as a lab guide for learning object oriented programming concepts.

Uploaded by

ahmadirtaza10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

OOP LAB Manual

The document discusses object oriented programming concepts like classes, objects, inheritance, polymorphism and strings. It contains details about arrays, classes, access specifiers, inheritance types and polymorphism types with examples. The document is intended as a lab guide for learning object oriented programming concepts.

Uploaded by

ahmadirtaza10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Object Oriented Programming Lab

CSL-121

Department of Computer Science

Institute of Management Sciences, Pak AIMS


Lahore
Contents
Lab 1: Arrays & its types.......................................................................................................................... 3
Array.................................................................................................................................................... 3
One Dimensional Array ....................................................................................................................... 3
Two Dimensional Array ....................................................................................................................... 4
Lab 2: Object Oriented Programming ..................................................................................................... 5
Classes and Objects ............................................................................................................................. 6
Lab 3: Inheritance ................................................................................................................................... 8
Inheritance .......................................................................................................................................... 8
Types of Inheritance in C++: ............................................................................................................... 8
1. Single Inheritance: .................................................................................................................. 8
2. Multiple Inheritance: .............................................................................................................. 9
3. Multilevel Inheritance: ............................................................................................................ 9
4. Hierarchical Inheritance: ....................................................................................................... 10
Lab 4: Polymorphism ............................................................................................................................ 10
Polymorphism ................................................................................................................................... 10
Types of Polymorphism..................................................................................................................... 10
Compile Time Polymorphism ............................................................................................................ 10
Function Overloading .................................................................................................................... 11
Operator Overloading ................................................................................................................... 12
Runtime Polymorphism .................................................................................................................... 14
Function Overriding ...................................................................................................................... 14
Lab 5: String .......................................................................................................................................... 15
String ................................................................................................................................................. 15
Lab 1: Arrays & its types

Array

Arrays are used to store multiple values in a single variable, instead of


declaring separate variables for each value.

To declare an array, define the variable type, specify the name of the array
followed by square brackets and specify the number of elements it should
store:

string cars[4];

We have now declared a variable that holds an array of four strings. To insert
values to it, we can use an array literal - place the values in a comma-
separated list, inside curly braces:

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

One Dimensional Array


A 1-dimensional array is a linear data structure in the C programming language,
consisting of a fixed number of elements of the same data type, stored in contiguous
memory locations.

Program:
A Program for sorting a 1 D array in ascending order.
#include<iostream>
using namespace std;
int main()
{
int num[10]={6,7,8,3,4,5,1,2,9,0};
int c;
for(int i=0;i<10;i++)
{
for(int j=i+1;j<10;j++)
{
if(num[i]>num[j])
{
c=num[i];
num[i]=num[j];
num[j]=c;
}
}
cout<<num[i]<<”\t”;
}
return 0;
}

Output:
0 1 2 3 4 5 6 7 8
9

Two Dimensional Array


A two-dimensional array, also known as a 2D array, is a collection of data
elements arranged in a grid-like structure with rows and columns. Each element in the
array is referred to as a cell and can be accessed by its row and column indices/indexes.

Program:
A Program to calculate maximum and minimum from a 2 D Array.
#include<iostream>
using namespace std;
void maximum ( int r[3][3] ){
int d = r[0][0];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(r[i][j]>d){
d = r[i][j];
}
}
}
cout<<"Maximum is :"<<d;
}
int minimum ( int r[3][3] ){
int d = r[0][0];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(r[i][j]<d){
d = r[i][j];
}
}
}
return d;
}
int main(){
int x [3][3] = { {5, 3, 8},
{7, 9, 0},
{6, 2, 1} };
maximum(x);
cout<<"\nMinimum is :"<<minimum(x);
return 0;
}

Output:
Maximum is :9
Minimum is :0

Lab 2: Object Oriented Programming


OOP
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or functions that perform
operations on the data, while object-oriented programming is about creating objects that
contain both data and functions.

Object-oriented programming has several advantages over procedural programming:


• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
• OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes the
code easier to maintain, modify and debug.

Classes and Objects

In C++, Classes are used to define user-defined data types that encapsulate
data(attribute) and methods (functions) that operate on that data. Classes provide a way
to model real-world objects or concepts in code. The data members represent the state
or attributes of objects, while the member functions define the behavior or actions that
objects can perform.
Class is a combination of:
 Class Definition
 Objects
 Data Member
 Member Functions

Class Definition
A class is defined using the ‘class’ keyword followed by the class name. It can
contain various members such as data members, member functions, constructors, and
destructors. The definition starts with the keyword class, followed by the class name.
Like a structure, the body of the class is delimited by braces and terminated by a
semicolon.

Objects
Objects are instances of a class. When you create an object, memory is allocated
to store its data members, and you can invoke the member functions to perform
operations on the object.

Data Members
Data members are variables declared within the class, representing the attributes
or properties of objects. They can be of various data types, including type int, float, char
etc.

Member Functions
Member functions are functions declared within the class that operate on the data
members of objects. They define the behavior or actions that objects can perform.
Member functions can be public, private, or protected, controlling their accessibility from
outside the class.

Access Specifier
Access specifiers in C++ are keywords that control the visibility and accessibility
of class members (data members and member functions) from outside the class. C++
provides three access specifiers: ‘public’, ‘private’, and ‘protected’.

By default, if no access specifier is mentioned, class members are considered


private.
Program:
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class smallobj //define a class
{
private:
int somedata; //class data
public:
void setdata(int d) //member function to set data
{
somedata = d;
}
void showdata() //member function to display data
{
cout << “Data is “ << somedata << endl;
}
};
////////////////////////////////////////////////////////////////
int main()
{
smallobj s1, s2; //define two objects of class smallobj
s1.setdata(1066); //call member function to set data
s2.setdata(1776);
s1.showdata(); //call member function to display data
s2.showdata();

return 0;
}

Output:
Data is 1066
Data is 1776

Lab 3: Inheritance
Inheritance
Inheritance in C++ is a fundamental concept of object-oriented programming that
allows one class (called the derived or child class) to inherit properties and behaviors
from another class (called the base or parent class). This mechanism promotes code
reuse and the creation of a hierarchy among classes.

Syntax
class BaseClass {
// Base class members
};

class DerivedClass : access-specifier BaseClass {


// Derived class members
};

Types of Inheritance in C++:


1. Single Inheritance:
A derived class inherits from only one base class.
class Base {
// Base class members
};
class Derived : public Base {
// Derived class members
};

2. Multiple Inheritance:
A derived class inherits from more than one base class. This allows the derived class to
access members from all the inherited base classes.
class Base1 {
// Base class members
};

class Base2 {
// Another base class members
};

class Derived : public Base1, public Base2 {


// Derived class members
};

3. Multilevel Inheritance:
A class is derived from another derived class, creating a hierarchy of classes.
class Base {
// Base class members
};

class Derived1 : public Base {


// Derived class members
};

class Derived2 : public Derived1 {


// More derived class members
};
4. Hierarchical Inheritance:
Multiple classes are derived from a single base class.
class Base {
// Base class members
};

class Derived1 : public Base {


// Derived class members
};

class Derived2 : public Base {


// Another derived class members
};

Lab 4: Polymorphism

Polymorphism
The term “Polymorphism” is a combination of two words “Poly” means many,
and “morphism” details how something has the ability to change. Generically,
polymorphism explains how one object or condition can occur in several different forms.

Types of Polymorphism
Polymorphism can come into play both during code compilation and also during
runtime.

Compile Time Polymorphism


Compile time polymorphism takes place when a program is being compiled. C++
polymorphism occurs in this phase when either a function or an operator is overloaded.
This type of polymorphism is also known as static or early binding.
Compile time polymorphism comes in two forms in C++: function overloading and
operator overloading.
Function Overloading
Function overloading allows us to use the same function multiple times, with the
action or output of that function dependent on its assigned data type.

Program:
#include<iostream>
using namespace std;
void output(int dessert_num) {
cout<<"The number of desserts is "<<dessert_num<<endl;
}

void output(float prep) {


cout<<"Prep time is "<<prep<<" minutes"<<endl;
}

void output(string dessert) {


cout<<"The dessert is "<<dessert<<endl;
}
int main() {
int x; float y; string z;
cout<<"Input a number of desserts:"<<endl;
cin>>x;
cout<<"Input a a prep time to two decimal places:"<<endl;
cin>>y;
cout<<"Input a dessert's name:"<<endl;
cin>>z;

output(x);
output(y);
output(z);
return 0;
}

Output:
Input a number of desserts:
3
Input a a prep time to two decimal places:
3.56
Input a dessert's name:
Cookie
The number of desserts is 3
Prep time is 3.56 minutes
The dessert is Cookie

Operator Overloading
C++ allows us to add additional tasks to operators by using the operator keyword
followed by the operator itself. Operators cover a wide range of uses in C++, from
arithmetic to comparisons and logical statements. We can give a special meaning to an
operator for a particular class without changing its original meaning for the rest of the
program. We call this operator overloading.

Program:
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float imag;
public:
Complex(): real(0), imag(0){ }

void input()
{
cout << "Enter real and imaginary parts respectively:
";
cin >> real;
cin >> imag;
}
Complex operator - (Complex c2)
{
Complex temp;
temp.real = real - c2.real;
temp.imag = imag - c2.imag;
return temp;
}

void output()
{
if(imag < 0)
cout<<"Output Complex number: "<<real<< imag<<"i";
else
cout<<"Output Complex number: "<<real<<"+"<<
imag<<"i";
}
};
int main()
{
Complex c1, c2, result;
cout<<"Enter first complex number:\n";
c1.input();
cout<<"Enter second complex number:\n";
c2.input();

result = c1 - c2;
result.output();

return 0;
}

Output:
Enter first complex number:
Enter real and imaginary parts respectively: 10 3
Enter second complex number:
Enter real and imaginary parts respectively: 3 2
Output Complex number: 7+1i

Runtime Polymorphism
Runtime polymorphism in C++ uses function overriding and takes place while a
program is in the run state. In this form of polymorphism, the program has to discover
which definition of a function it needs to use based on the information in the main()
function. Since this happens during runtime, the process is slower compared to compile
time polymorphism.

Function Overriding
As we know, inheritance is a feature of OOP that allows us to create derived
classes from a base class. The derived classes inherit features of the base class.
Suppose, the same function is defined in both the derived class and the based
class. Now if we call this function using the object of the derived class, the function of the
derived class is executed.
This is known as function overriding in C++. The function in derived class
overrides the function in base class.

Program:
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};
int main() {
Derived derived1;
derived1.print();
return 0;
}

Output:
Derived Function

Lab 5: String

String
Strings are used for storing text.
A string variable contains a collection of characters surrounded by double quotes:
Example:
Create a variable of type string and assign it a value:
string greeting = "Hello";

To use strings, you must include an additional header file in the source code, the
<string> library:
Example:
#include <string>
string greeting = "Hello";

String Concatenation
The + operator can be used between strings to add them together to make a new string.
This is called concatenation:
Example:
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;

Output:
John Doe

Append
A string in C++ is actually an object, which contain functions that can perform certain
operations on strings. For example, you can also concatenate strings with the
append() function:

Example:
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
cout << fullName;

Output:
John Doe

String Length
To get the length of a string, use the length() function:
Example:
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();
//We can also use
cout << "The length of the txt string is: " << txt.size();

Output:
The length of the txt string is: 26
The length of the txt string is: 26

String Reverse
To reverse the string using loop, C++ Program is given below:

Program:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
cout << "Original string: " << str << endl;
int length = str.length();
for (int i = 0; i < length / 2; ++i) {
char temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
cout << "Reversed string: " << str << endl;

return 0;
}

Output:
Original string: Hello, World!
Reversed string: !dlroW ,olleH

You might also like