0% found this document useful (0 votes)
16 views12 pages

OOP Composition Exercises in C++

The document contains a series of programming exercises focused on composition in Object-Oriented Programming (OOP), illustrating how one class can contain objects of another class. Exercises include creating classes for Car and Engine, Library and Book, House and Room, Computer and Processor, and Author and Book, each demonstrating a 'has-a' relationship. Key concepts covered include composition, encapsulation, and object construction.

Uploaded by

af904250
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views12 pages

OOP Composition Exercises in C++

The document contains a series of programming exercises focused on composition in Object-Oriented Programming (OOP), illustrating how one class can contain objects of another class. Exercises include creating classes for Car and Engine, Library and Book, House and Room, Computer and Processor, and Author and Book, each demonstrating a 'has-a' relationship. Key concepts covered include composition, encapsulation, and object construction.

Uploaded by

af904250
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Below are some programming exercises focused on composition in Object-Oriented Programming (OOP).

In composition, one class contains objects of another class as member variables, representing a "has-a"
relationship between them.

Exercise 1: Car and Engine (Composition)

Objective:
Create a Car class that contains an Engine class as a member variable. The Car class should use the
Engine class to start the engine and drive the car.

Solution:

#include <iostream>

using namespace std;

// Engine class

class Engine {

private:

bool isRunning;

public:

// Constructor to initialize engine state

Engine() : isRunning(false) {}

// Method to start the engine

void start() {

isRunning = true;

cout << "Engine is now running." << endl;

// Method to stop the engine

void stop() {

isRunning = false;
cout << "Engine has stopped." << endl;

// Method to check engine status

bool isEngineRunning() {

return isRunning;

};

// Car class (composes an Engine)

class Car {

private:

Engine engine; // Car "has a" Engine

public:

// Method to start the car (start the engine)

void startCar() {

[Link]();

cout << "Car is ready to drive!" << endl;

// Method to stop the car (stop the engine)

void stopCar() {

[Link]();

cout << "Car has stopped!" << endl;

// Method to check if the car is running

bool isCarRunning() {
return [Link]();

};

int main() {

Car myCar;

[Link]();

[Link]();

return 0;

Exercise 2: Library and Book (Composition)

Objective:
Create a Library class that contains a collection of Book objects. The Library class should provide
functionality to add and remove books from the collection.

Solution:

#include <iostream>

#include <vector>

using namespace std;

// Book class

class Book {

private:

string title;

string author;

public:

// Constructor to initialize a book


Book(string t, string a) : title(t), author(a) {}

// Method to display book details

void display() const {

cout << "Title: " << title << ", Author: " << author << endl;

};

// Library class (composes a collection of Books)

class Library {

private:

vector<Book> books; // Library "has many" Books

public:

// Method to add a book to the library

void addBook(const Book& book) {

books.push_back(book);

cout << "Book added to library!" << endl;

// Method to remove a book by title

void removeBook(string title) {

for (auto it = [Link](); it != [Link](); ++it) {

if (it->getTitle() == title) {

[Link](it);

cout << "Book removed from library!" << endl;

return;

}
cout << "Book not found!" << endl;

// Method to display all books in the library

void displayBooks() const {

if ([Link]()) {

cout << "No books in the library." << endl;

return;

for (const auto& book : books) {

[Link]();

};

int main() {

// Create some Book objects

Book book1("1984", "George Orwell");

Book book2("To Kill a Mockingbird", "Harper Lee");

// Create a Library object

Library library;

// Add books to the library

[Link](book1);

[Link](book2);

// Display all books in the library

[Link]();
return 0;

Exercise 3: House and Room (Composition)

Objective:
Create a House class that contains multiple Room objects. Each Room should have a name (e.g.,
bedroom, kitchen) and an area. The House class should allow displaying information about all rooms.

Solution:

#include <iostream>

#include <vector>

using namespace std;

// Room class

class Room {

private:

string name;

double area;

public:

// Constructor to initialize room

Room(string n, double a) : name(n), area(a) {}

// Method to display room details

void display() const {

cout << "Room: " << name << ", Area: " << area << " square meters" << endl;

};
// House class (composes multiple Rooms)

class House {

private:

vector<Room> rooms; // House "has many" Rooms

public:

// Method to add a room to the house

void addRoom(const Room& room) {

rooms.push_back(room);

cout << "Room added to house!" << endl;

// Method to display all rooms in the house

void displayRooms() const {

if ([Link]()) {

cout << "No rooms in the house." << endl;

return;

for (const auto& room : rooms) {

[Link]();

};

int main() {

// Create Room objects

Room room1("Living Room", 25.5);

Room room2("Kitchen", 15.0);

Room room3("Bedroom", 18.0);


// Create House object

House house;

// Add rooms to the house

[Link](room1);

[Link](room2);

[Link](room3);

// Display all rooms in the house

[Link]();

return 0;

Exercise 4: Computer and Processor (Composition)

Objective:
Create a Computer class that contains a Processor class. The Processor class should have a method to
display its speed, and the Computer class should use the processor to display the computer's processing
power.

Solution:

#include <iostream>

using namespace std;

// Processor class

class Processor {

private:

double speed; // Processor speed in GHz

public:
// Constructor to initialize speed

Processor(double s) : speed(s) {}

// Method to display processor speed

void displaySpeed() const {

cout << "Processor Speed: " << speed << " GHz" << endl;

};

// Computer class (composes a Processor)

class Computer {

private:

Processor processor; // Computer "has a" Processor

public:

// Constructor to initialize processor

Computer(double speed) : processor(speed) {}

// Method to display computer specs

void displaySpecs() const {

cout << "Computer Specs:" << endl;

[Link]();

};

int main() {

// Create a Computer object with a Processor of 3.5 GHz

Computer myComputer(3.5);
// Display computer specs

[Link]();

return 0;

Exercise 5: Author and Book (Composition)

Objective:
Create a Book class that contains an Author class. The Book should display the author's name and the
title of the book.

Solution:

#include <iostream>

using namespace std;

// Author class

class Author {

private:

string name;

public:

// Constructor to initialize author

Author(string n) : name(n) {}

// Method to get author's name

string getName() const {

return name;

};
// Book class (composes an Author)

class Book {

private:

string title;

Author author; // Book "has an" Author

public:

// Constructor to initialize title and author

Book(string t, Author a) : title(t), author(a) {}

// Method to display book and author details

void display() const {

cout << "Book: " << title << ", Author: " << [Link]() << endl;

};

int main() {

// Create an Author object

Author author("J.K. Rowling");

// Create a Book object

Book book("Harry Potter and the Sorcerer's Stone", author);

// Display book and author details

[Link]();

return 0;

}
Key Concepts Covered:

 Composition: One class contains objects of another class as member variables, representing a
"has-a" relationship.

 Encapsulation: Using classes to encapsulate behavior and data, keeping it hidden from the
outside world.

 Object Construction: Initializing and constructing complex objects that consist of multiple
components (classes).

These exercises will help you understand how objects can be composed of other objects, which is an
essential concept in OOP.

Common questions

Powered by AI

Object initialization methods vary by encapsulating relevant attributes via constructors. The Car class initializes its Engine inline, hiding specific engine initial state details . The House class uses a vector constructor to individually add Room objects . The Computer class initializes the Processor using a specific speed value, showing parameterized construction . Despite differences, all employ constructor functions to encapsulate initialization logic, ensuring the objects start in a valid state by default .

The 'has-a' relationship, also known as composition, is shown when one class contains objects of another class. For example, the Car class 'has-a' Engine as a member variable, meaning the Car relies on its Engine to function, but both remain distinct entities . This relationship indicates that the Car forms a whole, composed of an Engine, allowing separate lifecycle management of the components .

Encapsulation in the Book and Library classes is implemented by using private member variables and public methods. In the Book class, properties like 'title' and 'author' are private, ensuring they cannot be directly accessed from outside the class. Instead, methods are provided for interaction, such as 'display()' to show book details . The Library class controls access to its collection using methods like 'addBook()' and 'removeBook()', thus maintaining and modifying its state securely .

In OOP, composition allows for building complex objects by combining simpler ones. This promotes reusability because individual components, like the Engine in the Car exercise, can be utilized across different systems without rewriting code . It enhances flexibility as it supports object customization by altering component combinations, thus adapting to varying requirements without affecting the entire system .

The separation of concerns is achieved by assigning specific responsibilities to distinct classes. The Processor class focuses on managing attributes about processor speed and methods related to it, such as 'displaySpeed()'. Meanwhile, the Computer class is responsible for the overall computer specifications, incorporating a Processor object to fulfill its role of displaying detailed specs . This design encapsulates functionalities in coherent modules, reducing interdependence and enhancing maintainability .

Removing a book by title in the Library class can be challenging if multiple books have the same title or if the title is not present. This could lead to incorrect removals or failures to remove the intended book. A potential solution is to enhance the method to also check for unique identifiers (e.g., book ID) or author names to accurately locate the book in the collection .

Using public methods like 'display()' in the Room class allows external entities to access and utilize room details openly, adhering to encapsulation by protecting access to underlying data. Alternatives might involve providing getter methods to retrieve data for display externally, facilitating customization of display logic by the calling function. This variation could allow for more flexible UI integrations, albeit demanding greater control from the user over presentation logic .

Using vectors to store objects like Books or Rooms can introduce memory management issues, especially with large collections, as vectors dynamically resize which could lead to fragmented memory. Furthermore, sequential searches in large vectors can be inefficient. These issues might be mitigated by using alternative data structures like maps for faster lookups or employing smart pointers to manage memory more efficiently .

Encapsulating engine status within the Engine class contributes to system robustness by protecting the state integrity from unauthorized changes, restricting modifications to controlled methods like 'start()' or 'stop()'. This prevents inconsistent states in the Car class that relies on the Engine. Moreover, encapsulation leads to efficiency in maintenance as changes to engine behavior are localized to the Engine class without affecting other system parts .

Composing a Book with an Author using direct object composition ensures the Book includes complete Author information, simplifying data management, and ensuring no null references. This can be advantageous for ease of access and managing fixed relationships . However, it might lead to inefficiencies if multiple books by the same author exist, as Author details would be duplicated across Books. Instead, using pointers could reduce memory usage by sharing Author information among Books, though it introduces potential risks of dangling pointers or null references .

You might also like