BSEE21036 Lab18a Oop

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

Electrical Engineering Department - ITU

CS152L: Object Oriented Programming Lab

Course Instructor: Nadir Abbas Dated:

Semester: Summer 2023


Lab Engineer: Usama Riaz
Session: Batch:

Lab 18. Understanding Polymorphism and Virtual Inheritance in


C++

Name Roll number Obtained


Marks/100

Muhammad Sami Ullah BSEE21036

Checked on: ____________________________

Signature: ____________________________
Objective
The objective of this lab is to observe the basic knowledge of programming in C++.
Equipment and Component
Component Value Quantity
Description
Computer Available in lab 1

Conduct of Lab
1. Students are required to perform this experiment individually.
2. In case the lab experiment is not understood, the students are advised to seek help from
the course instructor, lab engineers, assigned teaching assistants (TA) and lab
attendants.

Theory and Background


Classes and objects are fundamental concepts in object-oriented programming (OOP). They are
the building blocks used to model real-world entities and their interactions in software
development.A class is a blueprint or a template that defines a new data type. It encapsulates the
data (attributes or properties) and behaviors (methods or functions) that the objects of that class
will possess. In other words, a class defines the structure and behavior of objects of a specific
type.
An object is an instance of a class. It is a concrete representation of the class and represents a
specific entity in the real world. Objects have their own unique data (attribute values) and can
perform actions (call methods) as defined in their class.

Polymorphism is a fundamental concept in object-oriented programming that allows objects of different


classes to be treated as objects of a common base class. It enables the same method or function to produce
different behaviors based on the actual type of the object at runtime. There are two types of
polymorphism: compile-time (function overloading) and runtime (function overriding through virtual
functions).

Virtual inheritance is a mechanism in C++ used to resolve the "diamond problem," which occurs when a
class inherits from two classes that share a common base class. Virtual inheritance ensures that only one
copy of the common base class is shared among the derived classes, preventing ambiguity and redundant
data. It is achieved by using the virtual keyword during the inheritance declaration.
Lab Task
Part A [Marks: 5]

Please follow the following steps before starting below tasks:


 Create function.h file for declaration of all functions
 Create function.cpp file to define define all declared functions.
 Create main.cpp file for driving code/call functions.

Note: Make a menu driven program (compulsory).

Part B: Understanding of Association Relationships [Marks: 35]


1. Create a C++ program that demonstrates polymorphism using classes. Define a base class
called Shape with a pure virtual function calculateArea() that calculates and returns the
area of the shape.
Then, create two derived classes Rectangle and Circle from the Shape class. Implement
the calculateArea() function in each derived class to calculate the area of a rectangle and
a circle, respectively.
In the main function, create objects of both Rectangle and Circle classes and store them
in an array of pointers to the base class Shape (using DMA). Use a loop to iterate through
the array and call the calculateArea() function for each shape. Display the area of each
shape on the screen.
2. Create a C++ program to implement a shape hierarchy using virtual inheritance. Define a
base class called Shape with pure virtual functions getArea() and display().
Then, create three derived classes: Rectangle, Circle, and Triangle, each inheriting
virtually from the Shape class. Implement the getArea() function in each derived class to
calculate and return the area of the corresponding shape (i.e., rectangle, circle, or
triangle). Implement the display() function to display the details of the shape, such as its
type and area.
In the main function, create objects of the Rectangle, Circle, and Triangle classes. Use
an array to store pointers to these objects of the Shape type. Iterate through the array, and
call the display() function for each shape to print its details, including its type,
dimensions, and calculated area.

// Paste your code here


// task01
#include <iostream>//preproccessar
#include <cmath>
using namespace std;//cout library
class Shape1 {// base class
public:
virtual ~Shape1() {} // destructor for proper cleanup in derived classes
virtual double calculateArea() const = 0;// virtual function
};

class Rectangle1 : public Shape1 {// chiled class


private:// private data
double Length1;// declaration
double Width1;// declaration

public:// public data


Rectangle1(double L1, double W1) : Length1(L1), Width1(W1) {}

double calculateArea() const


{

return Length1 * Width1;// returning area


}
};

class Circle1 : public Shape1 {// chiled class


private:// private data
double Radius1;// ddeclaration

public: // public data


Circle1(double r) : Radius1(r) {}

double calculateArea() const {


return M_PI * Radius1 * Radius1;// finding the Radius
}
};

int main() {// start of main function


float lengt, wid, rad;// declaration
cout<<"Enter the length"<<endl;// output and moving to next line
cin>>lengt;//input from user
cout<<"Enter the width"<<endl;// output and moving to next line
cin>>wid;//input from user
cout<<"Enter the radius"<<endl;// output and moving to next line
cin>>rad;//input from user
const int numberShapes = 2;// intialization
Shape1** shapes1 = new Shape1*[numberShapes];// pointer

shapes1[0] = new Rectangle1(lengt, wid);


shapes1[1] = new Circle1(rad);

for (int i = 0; i < numberShapes; ++i) {// for loop condition


cout << "Area of Shape " << i + 1 << ": " << shapes1[i]->calculateArea() <<endl;// output and
moving to next line
}

// Clean up memory
for (int i = 0; i < numberShapes; ++i) {// for loop condition
delete shapes1[i];// deleting the shape
}
delete[] shapes1;

return 0;// main end


}

//task02
#include <iostream>// preproceesar
#include <cmath>
using namespace std;// cout library

class Shape {// base class


public:
virtual ~Shape() {} // Virtual destructor for proper cleanup in derived classes
virtual double getArea() const = 0;
virtual void display() const = 0;
};

class Rectangle : virtual public Shape {// public class


protected:
double Length;// declaration
double Width;// declaration

public:
Rectangle(double L, double W) : Length(L), Width(W) {}

double getArea() const override {


return Length * Width;
}

void display() const override {


cout << "Shape: Rectangle, Length = " << Length << ", Width = " << Width << ", Area =
" << getArea() <<endl;
}
};

class Circle : virtual public Shape {


protected:
double Radius;

public:
Circle(double r) : Radius(r) {}
double getArea() const override {
return M_PI * Radius * Radius;
}

void display() const override {


std::cout << "Shape: Circle, Radius = " << Radius << ", Area = " << getArea() <<endl;//
output
}
};

class Triangle : virtual public Shape {// chiled class


protected:
double Base;// declaration
double Height;// declaration

public:
Triangle(double B, double H) : Base(B), Height(H) {}

double getArea() const override {


return 0.5 * Base * Height;// Triangle area
}

void display() const override {


cout << "Shape: Triangle, Base = " << Base << ", Height = " << Height << ", Area = " <<
getArea() << endl;// output
}
};

int main() {
float RectL, RectW, TriangB, TriangH, Rad;//// declaration
cout<<"Enter the length of Rectangle"<<endl;// output and moving to next line
cin>>RectL;// input from user
cout<<"Enter the Width of Rectangle"<<endl;// output and moving to next line
cin>>RectW;// input from user
cout<<"Enter the Base of Triangle"<<endl;// output and moving to next line
cin>>TriangB;// input from user
cout<<"Enter the Height of Triangle"<<endl;// output and moving to next line
cin>>TriangH;// input from user
cout<<"Enter the Radius"<<endl;// output and moving to next line
cin>>Rad;// input from user

const int numShapes = 3;


Shape* shapes[numShapes];

shapes[0] = new Rectangle(RectL, RectW);// passing value


shapes[1] = new Circle(Rad);// passing value
shapes[2] = new Triangle(TriangB, TriangH);// passing value
for (int i = 0; i < numShapes; ++i) {// for loop condition
shapes[i]->display();// displaying
}

// Clean up memory
for (int i = 0; i < numShapes; ++i) {// for loop condition
delete shapes[i];
}

return 0;
}

// Paste your output here

//task02
Assessment Rubric for Lab

Performance Max Obtained


Task CLO Description Exceeds expectation Meets expectation Does not meet expectation
metric marks marks
Executes without errors Executes without errors, user
Does not execute due to syntax
excellent user prompts, prompts are understandable,
errors, runtime errors, user
1. Realization good use of symbols, minimum use of symbols or
1 1 Functionality 40 prompts are misleading or non-  
of experiment spacing in output. Through spacing in output. Some
existent. No testing has been
testing has been completed testing has been completed
completed (0-19)
(35-40) (20-34)
Actively engages and Cooperates with other group
Distracts or discourages other
Group cooperates with other member(s) in a reasonable
2. Teamwork 1 3 5 group members from conducting  
Performance group member(s) in manner but conduct can be
the experiment (0-1)
effective manner (4-5) improved (2-3)
On Spot Able to make changes (8- Partially able to make
1 1 10 Unable to make changes (0-4)  
3. Conducting Changes 10) changes (5-7)
experiment Answered all questions (8- Unable to answer all questions
1 1 Viva/Quiz 10 Few incorrect answers (5-7)  
10) (0-4)
4. Laboratory
Comments are added and Comments are added and
safety and Code
1 3 5 does help the reader to does not help the reader to Comments are not added (0-1)  
disciplinary commenting
understand the code (4-5) understand the code (2-3)
rules
Excellent use of white
space, creatively organized Includes name, and
Poor use of white space
work, excellent use of assignment, white space
5. Data (indentation, blank lines) making
1 3 Code Structure 5 variables and constants, makes the program fairly easy  
collection code hard to read, disorganized
correct identifiers for to read. Title, organized work,
and messy (0-1)
constants, No line-wrap (4- good use of variables (2-3)
5)
Solution is efficient, easy A logical solution that is easy
6. Data A difficult and inefficient
1 4 Algorithm 20 to understand, and maintain to follow but it is not the most  
analysis solution (0-5)
(15-20) efficient (6-14)
Documentation
7. Computer
1 2 & GitHub 5 Timely (4-5) Late (2-3) Not done (0-1)  
use
Submissions
  Max Marks (total): 100 Obtained Marks (total):  

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy