0% found this document useful (0 votes)
7 views13 pages

UNIT 3 NEW OOSD

Uploaded by

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

UNIT 3 NEW OOSD

Uploaded by

st250403
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 13

In C++, you can translate object-oriented classes into various types of data structures depending

on the design

1. Classes to Structs
A struct in C++ is similar to a class, but its members are public by default (whereas, in a
class, they are private by default).
Associations and Encapsulation in Object-Oriented Design

In object-oriented design, associations and encapsulation are two key concepts that help organize and structure
data, relationships, and behaviors.

1. Associations
Associations refer to the relationships between objects (or classes). These relationships define how one object
is connected or related to another. In object-oriented programming (OOP), associations can be:
•One-to-One
•One-to-Many
•Many-to-One
•Many-to-Many
#include <iostream>
// Method to add a book to the library
#include <cstring> void addBook(Book* book) {
// Book class (represents a book) if (bookCount < 10) {
class Book { books[bookCount++] = book; // Add book to the array
public: } else {
std::cout << "Library is full!" << std::endl;
char title[100];
}
// Constructor to initialize the book's title
}
Book(const char* title) {
// Method to display all books in the library
strncpy(this->title, title, sizeof(this->title) - 1);
void displayBooks() const {
this->title[sizeof(this->title) - 1] = '\0'; // Ensure nullstd::cout << "Books in the Library:\n";
termination for (int i = 0; i < bookCount; ++i) {
} books[i]->displayInfo(); // Call displayInfo() for each book
// Method to display book information }
void displayInfo() const { }
std::cout << "Book Title: " << title << std::endl; };
}
};
// Library class (holds multiple books)
class Library {
private:
Book* books[10]; // Array of pointers to Book objects (up to 10 books)
int bookCount; // Number of books in the library
public:
// Constructor to initialize the library with no books
Library() : bookCount(0) {}
int main() {
// Create books
Book book1("1984");
Book book2("Brave New World");
Book book3("The Catcher in the Rye");

// Create a library
Library library;

// Add books to the library


library.addBook(&book1);
library.addBook(&book2);
library.addBook(&book3);

// Display all books in the library


library.displayBooks();

return 0;
}
Encapsulation in Data Structures:

When transitioning from classes to data structures, encapsulation is often sacrificed for simplicity and
performance. While you might not have the same strict data protection and behavior management, you can still
use functions to enforce certain behaviors or provide controlled access to the data.

For example, in the Student and Course example above, the encapsulation is not as strict. Instead of using a class
to encapsulate behavior (like enrolling a student), we just use data structures and functions. However, you can
still ensure controlled access to the data by using functions that manipulate the structure, like enroll() in the
Course class.
1. Reusability

Reusability refers to the ability to use a piece of code or a component (such as a class, function, or module) in
different programs or parts of the same program without modification.

Key Strategies for Achieving Reusability:


•Modularization: Break your code into small, self-contained units (e.g., classes or functions). A well-defined
class or function can be reused in multiple places.
. Encapsulation: By keeping the internals of a class hidden (via private members) and only exposing a well-
defined public interface, you can reuse the class in different scenarios.
•Templates (in C++): C++ templates allow you to write generic code that works with any data type, making it
reusable for multiple types.
class Car
{
void display() const
{
std::cout << year << " " << make << " " << model <<
std::endl;
}
// A function that can take any object of type Car and display
it
void displayCarInfo(const Car& car)
{
car.display();
}
int main()
{
Car car1("Toyota", "Camry", 2020);
Car car2("Honda", "Civic", 2021);

// Reusing the same function for different Car objects


displayCarInfo(car1);
displayCarInfo(car2);

return 0;
}
2. Extensibility
Extensibility refers to the ability to extend or modify the system easily without making major changes to the
existing code.

Key Strategies for Achieving Extensibility:


•Inheritance (OOP): You can create new classes that inherit from existing ones. This allows you to reuse code
and add new behavior without changing the base class.
•Polymorphism: Using polymorphism, you can design your system to work with objects of various derived
types through a common base class. This allows new types to be introduced without modifying existing code.
•Abstract Interfaces: By defining abstract interfaces or base classes, you make it easier to extend your system
by implementing new classes that adhere to these interfaces.
3. Robustness
Robustness refers to the ability of a system to handle errors, edge cases, and unexpected inputs gracefully without
crashing. Robust code is resilient to failures and is able to recover from issues, maintaining proper functionality
even in the face of challenges.
Key Strategies for Achieving Robustness:
• Error Handling: Use mechanisms like try-catch blocks, error codes, or assertions to catch and handle
exceptions or unexpected conditions.
• Validation: Validate inputs and ensure that the system operates within the expected range or conditions.
• Testing: Rigorous testing (unit tests, integration tests) helps identify potential issues early.
Abstraction and Encapsulation are two of the core principles in Object-Oriented Programming (OOP). While
they are closely related, they focus on different aspects of how you design and interact with classes and objects.

1. Abstraction Key Points of Abstraction:

· Hides Complexity: By hiding the internal workings of a class and exposing only the necessary methods,
abstraction helps in managing complexity.
· Focus on Behavior: The goal is to define what an object can do (its behavior) rather than how it achieves
those actions.
· Interfaces or Abstract Classes: In many languages, abstract classes or interfaces are used to define abstract
behavior that must be implemented by subclasses.
// Derived class: Rectangle
class Rectangle : public Shape
Abstraction Example {
#include <iostream> public:
// Abstract base class void draw() const override
class Shape { {
public: std::cout << "Drawing a Rectangle!" << std::endl;
// Pure virtual function (makes this class abstract) }
virtual void draw() const = 0; };

// Destructor int main()


virtual ~Shape() {} {
}; // Create objects of derived classes
Shape* shape1 = new Circle();
// Derived class: Circle Shape* shape2 = new Rectangle();
class Circle : public Shape
{ shape1->draw(); // Output: Drawing a Circle!
public: shape2->draw(); // Output: Drawing a Rectangle!
void draw() const override {
std::cout << "Drawing a Circle!" << std::endl; delete shape1;
} delete shape2;
};
return 0;
}
Differences Between Abstraction and Encapsulation
While both abstraction and encapsulation deal with hiding information, they serve different purposes:
•Abstraction focuses on hiding complexity by providing a simplified interface that only exposes the relevant details. It's
about defining "what" an object does (its behavior) and leaving the "how" (the implementation details) to be handled
internally or by derived classes.
Example: The Shape class defines a general contract (behavior of draw()), but the implementation details are left to the
derived classes (Circle, Rectangle).
•Encapsulation is about hiding data by restricting direct access to the internal state of an object and ensuring that it is
only accessed and modified in a controlled manner. It's about defining how data is manipulated, typically through
getter and setter methods.
Example: The BankAccount class encapsulates the balance and ensures that it cannot be directly modified from outside
the class. Instead, changes to the balance are made through controlled methods like deposit and withdraw.

You might also like