Data Encapsulation and Abstraction in Object-Oriented Programming
Classified in Technology
Written at on English with a size of 2.78 KB.
Data Encapsulation and Abstraction
Data encapsulation hides data from users, making it accessible only through class methods. This promotes abstraction, allowing users to utilize functionalities without needing to understand their internal workings.
Method Classification
Methods can be categorized into three groups:
- Constructors/Destructors: Initialize and finalize objects.
- Modifiers: Change data member values.
- Inspectors: Return object state information without altering it.
Friend Functions
Friend functions bridge the gap between unrelated functions and classes, enabling external access to private data members when necessary.
Inline Functions
Inline functions replace function calls with their code, offering advantages like method and friend compatibility, as well as overload capabilities. However, they can increase program size.
Pure Virtual Functions
Defined in base classes and redefined in derived classes, pure virtual functions ensure consistent method definitions across inheritance hierarchies without inheriting the base class implementation.
Inheritance Example
class Nom_claseDerivada : virtual tipo_derivacion Nom_claseBase {
// class code
};
Composition vs. Inheritance
Composition involves embedding an existing class object within a new class, establishing a "has-a" relationship. Inheritance, conversely, creates a new class as an extension of an existing one, forming an "is-a" relationship. The derived class inherits all base class members while adding its own.
Inheritance Access Specifiers
class Nom_clase_derived : tipo_derivacion Nom_clase_base {
// Public, private, and protected members
};
- Public → Private
- Protected → Private
- Private → Inaccessible
Example: Private Inheritance
If the inheritance type is private:
- Public members of the base class become private in the derived class.
- Protected members of the base class become private in the derived class.
- Private members of the base class are inaccessible in the derived class.
// ejemplo.cpp
mi_base.print2(); // Protected, acts like private, cannot be used
mi_derivado.print(); // Incorrect, access is private
printf("%d", mi_base.un_dato); // Protected, acts like private, cannot be used
printf("%d", mi_derivado.dato_publico); // Public in base, but private in derived
printf("%d", mi_base.dato_publico); // Accessible if public and within the base class
// derivada.cpp
void Derived::metodo_d() {
un_dato = 0; // Protected, but accessible within the derived class
otro_dato = 0; // Inaccessible
}