Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Task 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

SERNA LOPEZ JUAN ROBERTO MEC 5D

TASK 3: CLASSES AND


OBJECTS IN C++
UNIVERSIDAD TECNOLÓGICA DE ALTAMIRA 17/04/2024

1. Classes and Methods: Definitions and Types


In C++, classes and methods are fundamental concepts of object-oriented programming
(OOP).

Classes:

Definition:

In C++, classes are user-defined data types that serve as blueprints for creating objects.
They encapsulate data for the object and functions (methods) to operate on that data.

1. Encapsulation:

Definition:

Encapsulation is the bundling of data and methods that operate on that data into a single unit,
called a class.

Purpose:

It allows data to be hidden from the outside world and accessed only through well-defined
interfaces (public methods), thus preventing unauthorized access and manipulation of data.

Example:

In a `BankAccount` class, the balance data member can be kept private, and methods such
as `deposit` and `withdraw` can provide controlled access to manipulate the balance.

2. Abstraction:

Definition:
Abstraction is the concept of hiding complex implementation details and providing a
simplified interface for the users of a class.

Purpose:

It allows users to interact with objects at a higher level of understanding, without needing to
understand the internal complexities of how the object works.

Example:

A `Car` class might provide methods like `startEngine` and `drive` without exposing the
intricacies of the engine or transmission system.

3. Constructors and Destructors:

Constructors:

Constructors are special member functions that initialize objects of a class. They have the
same name as the class and are automatically called when an object is created.

Types:

Default constructor (with no parameters), parameterized constructor (with parameters), copy


constructor (to initialize an object with another object of the same class).

Destructors:

Destructors are special member functions that are called when an object goes out of scope
or is explicitly deleted. They are used to release resources acquired by the object.

Purpose:

Constructors ensure that objects are properly initialized before use, while destructors ensure
that resources are properly cleaned up when objects are destroyed.

4. Inheritance:

Definition:

Inheritance is the process of creating a new class (derived class) from an existing class (base
class), inheriting its data members and member functions.

Purpose:
It promotes code reuse by allowing the derived class to inherit features from the base class
and extend or modify them as needed.

Example:

A `SavingsAccount` class can inherit from the `BankAccount` class, gaining access to its
methods for deposit and withdrawal while adding additional features specific to savings
accounts.

5. Polymorphism:

Definition:

Polymorphism allows objects of different classes to be treated as objects of a common base


class through inheritance. It enables a single interface to represent multiple underlying forms.

Types:

Compile-time polymorphism (achieved through function overloading and operator


overloading) and runtime polymorphism (achieved through virtual functions and function
overriding).

Example:

A `Shape` base class with virtual function `draw()` can be inherited by various shapes like
`Circle` and `Rectangle`, each implementing their own version of the `draw()` method.

Understanding these concepts allows for the effective utilization of classes in C++
programming, enabling the creation of robust, modular, and maintainable code.

Types:

1. Singleton Class:

Description:

A singleton class ensures that only one instance of the class is created and provides a global
point of access to that instance.

Characteristics:

It typically has a private constructor to prevent external instantiation.


It provides a static method to access the single instance, creating it if necessary.

It is often used for managing global resources or configuration settings.

Example:

A `Logger` class that manages logging throughout an application, ensuring that only one
logger instance is used across the system.

2. Factory Class:

Description:

A factory class is responsible for creating objects of other classes, encapsulating the object
creation process.

Characteristics:

It provides methods or static functions to create instances of various classes based on


certain criteria.

It abstracts the object creation logic from the client code, promoting loose coupling.

It can implement different object creation strategies, such as simple object instantiation or
object pooling.

Example:

A `ShapeFactory` class that creates instances of different geometric shapes (e.g., circles,
rectangles) based on user input or predefined parameters.

3. Interface Class:

Description:

An interface class defines a contract for a set of methods without providing implementations.

Characteristics:

It contains pure virtual functions that must be implemented by derived classes.

It serves as a blueprint for implementing common behaviors across multiple classes.


It enables polymorphism by allowing objects of different derived classes to be treated
uniformly.

Example:

An `Drawable` interface class with a pure virtual method `draw()` that must be implemented by
classes representing drawable objects, such as shapes or images.

4. Proxy Class:

Description:

A proxy class acts as a placeholder for another class, controlling access to it or adding
additional functionalities.

Characteristics:

It wraps an object of the original class and provides a similar interface.

It can implement access control, logging, lazy initialization, or caching without modifying the
original class.

It enables the separation of concerns by delegating responsibilities to different classes.

Example:

A `ImageProxy` class that delays the loading of images until they are actually requested,
reducing resource consumption.

5. Adapter Class:

Description:

An adapter class allows incompatible interfaces of existing classes to work together without
modifying their source code.

Characteristics:

It wraps an existing class and provides a new interface that is compatible with the client's
requirements.

It translates requests from the client into a format that the wrapped class can understand and
vice versa.
It promotes code reuse by enabling the integration of classes with different interfaces.

Example:

A `DatabaseAdapter` class that adapts a legacy database access API to conform to a modern
database access interface, enabling seamless integration with new systems.

6. Template Class:

Description:

A template class allows for the creation of generic classes that can work with any data type.

Characteristics:

It uses template parameters to specify types or values that will be determined when the class
is instantiated.

It enables the implementation of algorithms or data structures that are independent of specific
data types.

It promotes code reuse and flexibility by allowing the same class template to be used with
different data types.

Example:

A `Stack` class implemented using templates, allowing it to store elements of any data type.

Understanding these extended types of classes in C++ provides a broader perspective on


how classes can be designed and utilized to address various programming challenges and
design requirements. Each type of class offers unique capabilities and benefits, enabling
developers to create flexible, modular, and maintainable software solutions.

Another Types:

1. Member Functions: Functions declared within a class, also known as methods.

2. Data Members: Variables declared within a class, representing the class's attributes.

3. Constructors: Special member functions that initialize objects of a class. They have the
same name as the class and no return type.
4. Destructors: Special member functions that are called when an object goes out of scope
or is explicitly deleted. They have the same name as the class preceded by a tilde (~) and no
return type.

5. Static Members: Members of a class that are shared among all instances of the class.
They are declared using the static keyword.

6. Friend Functions: Functions that are not members of a class but have access to its private
and protected members. They are declared with the friend keyword.

Methods:

Definition:

Also known as member functions, methods are functions defined within a class to perform
operations on the class's data members. They provide the interface through which the outside
world interacts with the class.

Types:

1. Public Methods:

Description:

Public methods, also known as member functions, are accessible from outside the class and
can be called by objects of the class.

Characteristics:

They provide the primary interface for interacting with objects of the class.

They encapsulate behaviors and operations that can be performed on the class's data
members.

They can access both public and private data members of the class.

Example:

In a `BankAccount` class, public methods like `deposit()` and `withdraw()` allow users to
interact with the account by depositing money or withdrawing funds.

2. Private Methods:
Description:

Private methods are only accessible within the class and cannot be called by objects of the
class.

Characteristics:

They are used for internal implementation details and are not exposed to users of the class.

They encapsulate helper functions or operations that are necessary for the class's
functionality but should not be visible externally.

Example:

Within a `Date` class, private methods like `isValidDate()` and `incrementDay()` may be used
internally to validate dates and perform date calculations.

3. Protected Methods:

Description:

Protected methods are accessible within the class and its subclasses (derived classes) but
not from outside the class hierarchy.

Characteristics:

They provide a level of access between public and private methods, allowing subclasses to
access them for customization.

They are often used to implement common functionality that subclasses may need to override
or extend.

Example:

In a `Shape` base class, protected methods like `calculateArea()` and `calculatePerimeter()`


could be used by subclasses like `Circle` and `Rectangle` to calculate their specific
properties.

4. Static Methods:

Description:
Static methods belong to the class rather than to instances of the class and can be called
without creating an object of the class.

Characteristics:

They operate on class-level data and do not require access to object-specific data members.

They can be called using the class name rather than an object instance.

Example:

In a `Math` class, static methods like `Math::squareRoot()` and `Math::power()` perform


mathematical operations without needing to create a `Math` object.

5. Virtual Methods:

Description:

Virtual methods can be overridden in derived classes, enabling dynamic binding and
polymorphism.

Characteristics:

They allow for runtime determination of the appropriate method to call based on the actual
type of the object.

They enable the implementation of runtime polymorphism, where a base class pointer or
reference can refer to objects of different derived classes.

Example:

In an inheritance hierarchy, a base class `Animal` may have a virtual method `makeSound()`
overridden by derived classes like `Dog` and `Cat` to produce their specific sounds.

6. Const Methods:

Description:

Const methods promise not to modify the state of the object and are declared with the
`const` keyword at the end of the function declaration.

Characteristics:
They enable const-correctness by ensuring that objects can be accessed and manipulated
without altering their internal state.

They are especially useful for ensuring that objects can be accessed safely in const contexts,
such as when passing objects by const reference.

Example:

In a `Vector` class, a method like `size()` that returns the size of the vector without modifying it
could be declared as const.

Understanding these extended characteristics of methods in C++ is essential for designing


well-structured and maintainable object-oriented programs. Each type of method serves
specific purposes and offers unique capabilities for implementing various programming
paradigms and design patterns.

2. Syntax or Structure of a Class and a Method


Class Syntax:
In the class syntax:

Private data members are declared within the private: section and are accessible only within
the class.

Public data members are declared within the public: section and are accessible from outside
the class.

Constructors and destructors, if present, have the same name as the class and are used for
initializing and cleaning up class objects, respectively.

Public member functions (methods) are declared within the public: section and provide the
interface for interacting with class objects.

Method Syntax:

In the method syntax:

ReturnType specifies the data type that the method returns.

ClassName:: indicates that the method belongs to the class ClassName.

MethodName is the name of the method.

Parameters are optional parameters passed to the method.

The method body contains the code that defines the behavior of the method.

3. Examples in C++ Language Applying Classes and Methods


Example 1: Simple Class and Method
Demonstration:
This example demonstrates the basic concept of a class with methods.

Explanation:

We define a class Rectangle with private data members length and width.

The setDimensions method sets the dimensions of the rectangle.

The calculateArea method calculates the area of the rectangle.

In the main function, we create an object of the Rectangle class, set its dimensions, and
calculate its area.

Example 2: Class with Constructor and Destructor


Demonstration:

This example demonstrates the use of constructors and destructors in a class.

Explanation:

We define a class Example with a constructor that prints a message when an object is
created and a destructor that prints a message when an object is destroyed.

In the main function, we create an object of the Example class, which triggers the constructor
to be called. When the object goes out of scope, the destructor is called automatically.

Example 3: Class with Inheritance


Demonstration:
This example demonstrates inheritance, where a derived class inherits from a base class.

Explanation:

We define a base class Base with a display method.

We define a derived class Derived that inherits from the Base class and overrides the display
method.

In the main function, we create an object of the Derived class and call its display method.
Since the display method is overridden in the derived class, it prints the message specific to
the derived class.

These examples showcase different aspects of object-oriented programming in C++,


including encapsulation, constructors and destructors, and inheritance.

4. Conclusion
In conclusion, understanding classes in C++ is essential for developing robust and efficient
object-oriented programs. Classes provide a powerful mechanism for encapsulating data and
behavior, promoting code organization, reusability, and maintainability.

By encapsulating data within classes, programmers can control access to that data and
ensure its integrity through well-defined interfaces. This encapsulation, along with the
principles of abstraction, allows users of a class to interact with objects at a higher level of
understanding, without needing to understand the internal details of how the class works.

Constructors and destructors facilitate proper object initialization and cleanup, ensuring that
resources are acquired and released appropriately throughout the object's lifecycle.
Inheritance enables the creation of new classes that inherit properties and behaviors from
existing classes, promoting code reuse and extensibility.

Furthermore, polymorphism allows for the creation of flexible and adaptable code by enabling
objects of different classes to be treated uniformly through a common interface. This
facilitates dynamic binding and enables the implementation of runtime polymorphism, where
the appropriate method is determined at runtime based on the object's actual type.

In summary, classes in C++ are a foundational concept of object-oriented programming,


offering a rich set of features such as encapsulation, abstraction, inheritance, and
polymorphism. Mastery of these concepts empowers developers to design elegant, modular,
and maintainable software solutions to complex problems.

You might also like