V.Vidhya Logo

V.Vidhya

Object Relationships & Inheritance (OOP)


Q1.

The following program should run:

#include <iostream>

int main()
{
	Apple a{ "Red delicious", "red", 4.2 };
	a.printDetails();

	Banana b{ "Cavendish", "yellow" };
	b.printDetails();

	return 0;
}

And print the following:

Apple(Red delicious, red, 4.2)
Banana(Cavendish, yellow)

Q2.

And print the following:

Train: Rajdhani Express
Carriage[1: Sleeper, 40 seats]
Carriage[2: Seater, 72 seats]
Carriage[3: Dining, 20 seats]

Q3.

Analyze the given programs below, predict their outputs and determine whether they follow the principles of object-oriented programming correctly.


Q4.

What will be the output of the following programs?

You have to predict the output yourself without running/executing the code.


Q5.

Write an Apple class and a Banana class that are derived from a common Fruit class. Fruit should have two members: a name and a color.

The following program should run:

int main()
{
	Apple a{ "red" };
	Banana b{};

	std::cout << "My " << a.getName() << " is " << a.getColor() << ".\n";
	std::cout << "My " << b.getName() << " is " << b.getColor() << ".\n";

	return 0;
}

And produce the result:

My apple is red.
My banana is yellow.

Add a new class to the previous program called GrannySmith that inherits from Apple.

The following program should run:

int main()
{
	Apple a{ "red" };
	Banana b;
	GrannySmith c;

	std::cout << "My " << a.getName() << " is " << a.getColor() << ".\n";
	std::cout << "My " << b.getName() << " is " << b.getColor() << ".\n";
	std::cout << "My " << c.getName() << " is " << c.getColor() << ".\n";

	return 0;
}

And produce the result:

My apple is red.
My banana is yellow.
My Granny Smith apple is green.

Q6.

What will be the output of the following programs?

You have to predict the output yourself without running/executing the code.


Q7.

A computer shop needs a simple tool to keep track of each machine and its parts.

Create a program that:

Instructions

In your design you should:

  • Have a Computer class that holds its brand, model, one CPU and a list of MemoryModules.
  • Have a CPU class that stores its core count and clock speed.
  • Have a MemoryModule class that stores its capacity and a type chosen from a predefined set of memory types (use an enum for the types).
  • Let Computer provide a way to add memory modules.
  • Provide a way to print everything: the computer’s brand and model, the CPU’s specs and each memory module’s size and type.
  • In main(), demonstrate by:
    • Creating a computer (pick any brand and model).
    • Adding at least two memory modules of different sizes/types.
    • Printing the computer’s full details.
Expected Output
Computer: ThinkPad X1 Carbon
CPU: 6 cores @ 2.8 GHz
Memory Modules:
  - 16 GB DDR4
  - 32 GB DDR5

Q8.

A zoo wants to keep a registry of animals, organizing shared and unique information.

Create a program that:

Instructions
  • Create a base class Animal to store:
    • Name (e.g. “Sher Khan”)
    • Species (e.g. “Bengal Tiger”)
    • Age (e.g. 4)
    • Member functions to:
      • Display common media details.
  • Create a derived class Mammal that inherits from Animal and adds:
    • Fur Color (e.g. “Orange with Black Stripes”)
    • Is Endangered? (e.g. true/false)
    • Member functions to:
      • Display all common details plus additional details - fur color and endangered status.
  • Create another derived class Bird that inherits from Animal and adds:
    • Wing Span (in cm, e.g. 120)
    • Can Fly? (e.g. true/false)
    • Member functions to:
      • Display all common details plus additional details - wing span and flight capability.
  • In main(), demonstrate:
    • Creating one Mammal object (e.g. a tiger) and one Bird object (e.g. a penguin).
    • Setting all relevant details.
    • Displaying each animal’s full details.
Expected Output
// Mammal details:
Animal Details (Mammal):
Name: Sher Khan
Species: Bengal Tiger
Age: 4
Fur Color: Orange with Black Stripes
Endangered: Yes

// Bird details:
Animal Details (Bird):
Name: Pingi
Species: Emperor Penguin
Age: 2
Wing Span: 120 cm
Can Fly: No

Q9.

What will be the output of the following programs?

You have to predict the output yourself without running/executing the code.


Q10.

An e-learning platform wants to manage different types of courses (SelfPaced and LiveSession) using shared and unique information. Each course must enforce invariants (no negative prices or durations) and support behaviors like enrolling students, tracking progress, or scheduling sessions.

Create a program that:

Instructions
  • Create a base class Course to store:
    • Course Title (e.g. “Intro to C++”)
    • Course ID (e.g. “CSE101”)
    • Price (in ruppees, e.g. 15000.00)
    • Member functions to:
      • Display common course details.
  • Create a derived class SelfPacedCourse that inherits from Course and adds:
    • Total Video Hours (e.g. 10.5)
    • Number of Modules (e.g. 8)
    • Completed Modules (initially 0)
    • Member functions to:
      • Mark a module as completed, which increments the completed modules count, up to the total number of modules.
      • To know the progress percentage.
      • Display all the course details.
    • Getter and Setter functions for Total Video Hours and Number of Modules.
  • Create a derived class LiveSessionCourse that inherits from Course and adds:
    • Course Duration (in months, e.g. 3)
    • Max Class Size (e.g. 30)
    • Enrolled Students (initially 0)
    • Member functions to:
      • Enroll a student, which increments the enrolled students count, up to the max class size.
      • To check if the class is full.
      • Display all the course details.
    • Getter and Setter functions for Course Duration.
  • In main(), demonstrate:
    • Creating one SelfPacedCourse object, setting valid relevant details.
    • Display all the course details for it.
    • For SelfPacedCourse object, call complete module function several times and print the progress percent after each to show how progress increases.
    • Use the relevant access function to change the video hours of one course, then display the course details again to confirm the update.
    • Attempt to call complete module function enough times to exceed the total number of modules, and show that completed modules count never goes past its maximum.
    • Creating one LiveSessionCourse object, setting valid relevant details.
    • Display all the course details for it.
    • For LiveSessionCourse object, repeatedly call enroll student function, until the class is full and then attempt to enroll one more student to verify that enrollment is blocked when at capacity.
    • Finally, create one SelfPacedCourse and one LiveSessionCourse each with invalid inputs (e.g., empty title or ID, negative price, negative video hours, negative modules, negative class size, or enrolled > max).
    • Displaying each course’s full details.
    • Display all the course details for each to show how invalid values were replaced by defaults, verifying that class invariants work as intended.
Expected Output
// Self-Paced Course 1 details:
Course Details (SelfPaced):
Course: C++ Basics
ID: C101
Price: rs.25000.00
Video Hours: 30.50
Modules: 0 / 5 (0.00%)

// Completing modules for C++ Basics...
Completed module 1. Progress: 20.00%
Completed module 2. Progress: 40.00%
Completed module 3. Progress: 60.00%

// Updating video hours for C++ Basics to 36.00...
Course Details (SelfPaced):
Course: C++ Basics
ID: C101
Price: rs.25000.00
Video Hours: 36.00
Modules: 3 / 5 (60.00%)

// Completing remaining modules...
Completed module 4. Progress: 80.00%
Completed module 5. Progress: 100.00%
// Attempting extra module completion...
Modules: 5 / 5 (100.00%)


// Live Session Course 1 details:
Course Details (LiveSession):
Course: Graphics Design
ID: GD301
Price: rs.40000.00
Course Duration: 8 months
Class Size: 1 / 3 (Open)

// Enrolling student for Data Structures Live...
Enrollment successful.
Course Details (LiveSession):
Course: Graphics Design
ID: GD301
Price: rs.40000.00
Course Duration: 8 months
Class Size: 2 / 3 (Open)

// Enrolling one more student for Data Structures Live...
Enrollment successful.
Course Details (LiveSession):
Course: Graphics Design
ID: GD301
Price: rs.40000.00
Course Duration: 8 months
Class Size: 3 / 3 (Full)

// Attempting one more enrollment...
Enrollment failed. Class is full.

// Invalid Self-Paced Course details:
Course Details (SelfPaced):
Course: UNKNOWN
ID: UNKNOWN
Price: rs.0.00
Video Hours: 0.00
Modules: 0 / 0 (0.00%)

// Invalid Live Session Course details:
Course Details (LiveSession):
Course: UNKNOWN
ID: UNKNOWN
Price: rs.0.00
Scheduled Date: 
Class Size: 0 / 0 (Full)

Q11. (Adv.)

An online marketplace sells a wide variety of items, from physical goods to digital downloads. Each product shares some common information, but extends into different details and behaviors depending on its type. So the store manager needs a tool that helps him maintain a unified catalog of all products, check whether an item can be sold (based on stock or valid license) and process orders accordingly.

Instructions
  • Catalog Management
    • Your program should allow the manager to add new products to the catalog, specifying:
      • Common fields:
        • product ID (e.g. “P1001” or “D2001”)
        • product name (e.g. “Wireless Mouse” or “C++ eBook”)
        • unit price (e.g. 25.00)
      • If it’s a physical good:
        • shipping weight in kg (e.g. 0.2)
        • dimensions (length x width x height in cm, e.g. 10 x 5 x 3)
        • initial stock count (e.g. 50)
      • If it’s a digital download:
        • file size in MB (e.g. 5)
        • full download URL (e.g. “example.com/download/ebook”)
        • license validity date (in dd/mm/yyyy format, e.g. 31-12-2025)
    • After adding items, the manager can ask the program to display all products, which prints every product’s full information.
  • Availability Checking & Ordering
    • When a customer tries to order some quantity of a product (physical or digital), the program must:
      • Look up the product by ID.
      • If it’s a physical good:
        • Verify that the requested quantity is not more than the current stock.
        • If not enough stock, print an “Out of stock” or “Insufficient stock” message and decline the order.
        • If enough stock, calculate shipping cost = (weight x shipping - rate) x quantity. Use a fixed shipping rate of rs.5 per kg.
        • Reduce the product’s stock by the purchased quantity.
        • Print an order summary showing product name, quantity, unit price, shipping cost (breakdown per unit and total), total cost and the updated stock remaining.
      • If it’s a digital download:
        • Check today’s date (for e.g. assume the system date is “02-06-2025”) against the license validity date.
        • If today is after the license expiry date, decline the order with “License expired” or “Download not available.”
        • If the license is still valid, do not change any stock (digital items do not run out), but print an order summary showing product name, quantity, unit price, total cost and the download URL.
  • User Interaction Workflow
    • Add at least one physical product and one digital product to your catalog.
    • Display all products once after adding them.
    • Attempt these orders in sequence:
      • Order 2 units of the physical product.
      • Order 1 copy of the digital product.
      • Attempt to order more units of the physical product than remain in stock (to show the “insufficient stock” message).
      • Attempt to order the digital product again after the license has expired (to show the “License expired” message).
    • After each attempt, print the program’s response or order summary.
    • At the very end, display all products again so the manager sees updated stock for the physical good.
Expected Output
All Products:
-------------------------------
Product ID: P1001
Name: Wireless Mouse
Price: rs.500.00
Type: Physical
Weight: 0.225 kg
Dimensions: 10 x 5 x 3 cm
Stock: 50

Product ID: D2001
Name: C++ eBook
Price: rs.750.00
Type: Digital
File Size: 5.00 MB
Download Link: www.example.com/download/cppebook
License Valid Until: 31/12/2025

Ordering 2 x P1001 (Wireless Mouse)...
Availability check passed (stock 50 ≥ 2).
Shipping rate: rs.5.00 per kg
Weight per unit: 0.20 kg
Shipping per unit: 0.20 x rs.5.00 = rs.1.00
Total shipping for 2 units: rs.2.00

Order Summary (Physical Product):
---------------------------------
Product: Wireless Mouse
Quantity: 2
Unit Price: rs.500.00
Subtotal (price x quantity): rs.1000.00
Shipping Cost: rs.2.00
Total Cost: rs.1002.00
Remaining Stock for P1001: 48
---------------------------------

Ordering 1 x D2001 (C++ eBook)...
Current Date: 02/06/2025
License Valid Until: 31/12/2025
License is valid. Proceeding with download.

Order Summary (Digital Product):
---------------------------------
Product: C++ eBook
Quantity: 1
Unit Price: rs.750.00
Subtotal (price x quantity): rs.750.00
Download Link: www.example.com/download/cppebook
---------------------------------

Ordering 100 x P1001 (Wireless Mouse)...
Availability check failed. Requested: 100, In Stock: 48.
Insufficient stock! Order cannot be processed.

Ordering 1 x D2001 (C++ eBook)...
Current Date: 15/01/2026
License Valid Until: 31/12/2025
License expired! Download not available. Order declined.

All Products:
-------------------------------
Product ID: P1001
Name: Wireless Mouse
Price: rs.500.00
Type: Physical
Weight: 0.20 kg
Dimensions: 10 x 5 x 3 cm
Stock: 48

Product ID: D2001
Name: C++ eBook
Price: rs.750.00
Type: Digital
File Size: 5.00 MB
Download Link: www.example.com/download/cppebook
License Valid Until: 31/12/2025

Prev Post
Access Functions, Constructor & Destructor (OOP)