Documentos de Académico
Documentos de Profesional
Documentos de Cultura
https://www.geeksforgeeks.org/object-oriented-programming-in-cpp/
https://www.educba.com/software-development/software-development-tutorials/c-plus-plus-
programming-tutorial/
Sin embargo, los lenguajes modernos como C#, Java o... en realidad casi
cualquiera, utilizan otros paradigmas para definir los programas. Entre éstos,
el paradigma más popular es el que se refiere a la Programación Orientada
a Objetos o POO.
En este paradigma, los programas se modelan en torno a objetos que
aglutinan toda la funcionalidad relacionada con ellos. De este modo en lugar
de crear una serie de funciones sin conexión alguna entre ellas, en POO se
crean clases, que representan entidades que quieres manejar en tu
programa. Por ejemplo, facturas, líneas de factura, clientes, coches... o
cualquier entidad que necesites gestionar conceptualmente. En ese
sentido, la POO gira más en torno a los datos que en torno a la lógica,
que se delega a un segundo plano, ya que forma parte de dichos datos como
veremos enseguida.
La POO puede resultar confusa para mucha gente al principio, cuando se
entra en contacto con ella. Por eso me he animado a grabar el vídeo que
tienes al principio, y a escribir este artículo, en los que te voy a explicar con
las palabras más sencillas posibles los principales conceptos de la
Programación Orientada a Objetos, independientemente del lenguaje de
programación que utilices.
La clase define de forma genérica cómo son las personas, y los objetos son
personas concretas.
Vamos a verlos
Pilar 1: Encapsulación
Así, una clase (y por lo tanto todos los objetos que se crean a partir de ella)
debe exponer para su uso solo lo que sea necesario. Cómo se haga "por
dentro" es irrelevante para los programas que hagan uso de los objetos de
esa clase.
Otro ejemplo incluso más claro podría ser la acción Hablar(). Ésta puede
suponer que se genere una voz sintética a partir de un texto que se le indica
como parámetro de la acción para lo cual quizá ocurran un montón de cosas:
se llama a un componente para síntesis de voz que está en la nube, se lanza
la síntesis de voz en el dispositivo local de audio y se anota en una base de
datos la frase que se ha pronunciado para guardar un histórico entre otras
cosas. Pero todo esto es indiferente para el programa que hace uso de esta
funcionalidad. El programa simplemente tiene acceso a un
objeto Cristina y llama a la función Hablar(). No tiene ni idea de toda la
complejidad interna que puede suponer. Si mañana cambiamos el modo de
sintetizar la voz o cualquier otra acción interna, es indiferente para el
programa que usa nuestros objetos de tipo Persona.
La abstracción está muy relacionada con la encapsulación, pero va un paso
más allá pues no sólo controla el acceso a la información, sino también
oculta la complejidad de los procesos que estemos implementando.
Pilar 3: Herencia
Desde el punto de vista de la genética, cuando una persona obtiene de sus
padres ciertos rasgos (el color de los ojos o de la piel, una enfermedad
genética, etc...) se dice que los hereda. Del mismo modo en POO cuando
una clase hereda de otra obtiene todos los rasgos que tuviese la
primera.
Dado que una clase es un patrón que define cómo es y cómo se comporta
una cierta entidad, una clase que hereda de otra obtiene todos los rasgos de
la primera y añade otros nuevos y además también puede modificar
algunos de los que ha heredado.
A la clase de la que se hereda se le llama clase base, y a la clase que hereda
de ésta se le llama clase derivada.
Por ejemplo, los objetos de la clase Pirata tienen un método nuevo que
es Abordar() que en el juego sirve para asaltar un barco enemigo. Pero
además presentan una propiedad que solo tienen los piratas
llamada Sobrenombre, que es el nombre por el que se les conoce (un pirata
puede ser de nombre Hızır y de apellido bin Yakup pero su sobrenombre
es Barbaroja).
Pilar 4: Polimorfismo
1. ¿Qué es un objeto?
En el mundo real, estamos rodeados de objetos: tu taza de café, tu
teléfono, tu bicicleta. Estos objetos tienen características (color, tamaño,
modelo) y comportamientos (una taza contiene líquido, un teléfono
puede hacer llamadas). En POO, modelamos estas entidades reales como
"objetos" en código.
class Coche:
# Constructor de la clase
def init(self, marca, modelo):
self.marca = marca
self.modelo = modelo
# Método para describir el coche
def describir(self):
return f"Este coche es un {self.marca} {self.modelo}"
Ahora bien, cuando usas el molde para hacer una galleta, esa galleta
individual es un objeto. Aunque proviene de un molde común, cada
galleta es única y puede tener sus propias particularidades, como chispas
de chocolate o trocitos de nuez.
4. Atributos y métodos
Un mismo objeto 'Chico' puede tener varios atributos, diferentes o en común con respecto a otros
objetos de la misma clase
Piensa en cómo describirías a tu mejor amigo: tiene nombre, edad, color
de ojos, hobbies, etc. Estas características individuales son similares a
los atributos en POO. Es decir, son las propiedades específicas que un
objeto (como nuestra galleta) puede tener.
@abstractmethod
def apagar(self):
pass
class Bombilla(Encendible):
def encender(self):
print("Bombilla encendida!")
def apagar(self):
print("Bombilla apagada!")
Aquí, Encendible es nuestra interfaz que dicta que cualquier objeto que
pueda ser encendido y apagado debe tener los
métodos encender() y apagar(). La clase Bombilla implementa esta interfaz y
define cómo se enciende y se apaga una bombilla.
#include <stdio.h>
void Print(char c) {
printf("%c", c);
}
void Print(int i) {
printf("%i", i);
}
void Print(float f) {
printf("%f", f);
}
void Print() {
printf("\n"); // Nueva l¡nea
}
void main() {
int i= 1;
char c= 'a';
long l= 10L;
float f= 3.3;
char * s= "Hola, aprendices de magia con C++";
void * p= (void *)s;
Print(s);
Print();
Print(i);
Print();
Print(c);
Print();
Print(l);
Print();
Print(f);
Print();
Print(p); // Direcci¢n de la cadena
Print();
}
#include <stdio.h>
void main() {
int i;
char c;
long l;
float f;
void * p;
char s[100];
#include <stdio.h>
// Inline function in C
return 2;
int main()
int ret;
ret = foo();
printf("Output is: %d\n", ret);
return 0;
--------------------------------------------
#include <stdio.h>
// Inline function in C
return 2;
// Driver code
int main()
int ret;
ret = foo();
return 0;
#include <stdio.h>
// defining inline function with inline keywordfor addition
static inline int addition(int a, int b)
{
return a + b ; // returning the output value as per requirement
}
// Main user code
Int main()
{
inta, b, x ;
printf( " Please enter the value of integer a : " ) ;
scanf( "%d", &a ) ;
printf( " Please enter the value of integer b : " ) ;
scanf( "%d" , &b ) ;
// Calling the inline function by reference
x = addition( a , b ) ;
printf( " The result of addition of the given integers is : %d\
n " , x ) ;
return 0 ;
}
#include <stdio.h>
// defining inline function with inline keyword
static inline int subtraction(int a, int b)
{
return a - b ; // returning the output value as per requirement
}
// Main user code
Int main()
{
inta, b, x ;
printf( " Please enter the value of integer a : " ) ;
scanf( "%d", &a ) ;
printf( " Please enter the value of integer b : " ) ;
scanf( "%d" , &b ) ;
// Calling the inline function
x = subtraction( a , b ) ; // making a reference to inline
function.
printf( " The result of subtraction of the given integers is :
%d\n " , x ) ;
return 0 ;
}
#include <iostream>
using namespace std;
int main() {
cout << "Hello Welcome to C++ Programming";
return 0;
}
C++
class person {
char name[20];
int id;
public:
void getdetails() {}
};
int main()
{
Objects take up space in memory and have an associated address like a record in pascal
or structure or union. When a program is executed the objects interact by sending
messages to one another. Each object contains data and code to manipulate the data.
Objects can interact without having to know details of each other’s data or code, it is
sufficient to know the type of message accepted and the type of response returned by the
objects.
To know more about C++ Objects and Classes, refer to this article – C++ Classes and
Objects
Encapsulation
In normal terms, Encapsulation is defined as wrapping up data and information under a
single unit. In Object-Oriented Programming, Encapsulation is defined as binding
together the data and the functions that manipulate them. Consider a real-life example of
encapsulation, in a company, there are different sections like the accounts section, finance
section, sales section, etc. The finance section handles all the financial transactions and
keeps records of all the data related to finance. Similarly, the sales section handles all the
sales-related activities and keeps records of all the sales. Now there may arise a situation
when for some reason an official from the finance section needs all the data about sales in
a particular month. In this case, he is not allowed to directly access the data of the sales
section. He will first have to contact some other officer in the sales section and then
request him to give the particular data. This is what encapsulation is. Here the data of the
sales section and the employees that can manipulate them are wrapped under a single
name “sales section”.
Encapsulation in C++
Encapsulation also leads to data abstraction or data hiding. Using encapsulation also
hides the data. In the above example, the data of any of the sections like sales, finance, or
accounts are hidden from any other section.
To know more about encapsulation, refer to this article – Encapsulation in C++
Abstraction
Data abstraction is one of the most essential and important features of object-oriented
programming in C++. Abstraction means displaying only essential information and
hiding the details. Data abstraction refers to providing only essential information about
the data to the outside world, hiding the background details or implementation. Consider
a real-life example of a man driving a car. The man only knows that pressing the
accelerator will increase the speed of the car or applying brakes will stop the car but he
does not know how on pressing the accelerator the speed is actually increasing, he does
not know about the inner mechanism of the car or the implementation of an accelerator,
brakes, etc. in the car. This is what abstraction is.
Abstraction using Classes: We can implement Abstraction in C++ using
classes. The class helps us to group data members and member functions using
available access specifiers. A Class can decide which data member will be
visible to the outside world and which is not.
Abstraction in Header files: One more type of abstraction in C++ can be
header files. For example, consider the pow() method present in math.h header
file. Whenever we need to calculate the power of a number, we simply call the
function pow() present in the math.h header file and pass the numbers as
arguments without knowing the underlying algorithm according to which the
function is actually calculating the power of numbers.
To know more about C++ abstraction, refer to this article – Abstraction in C++
Polymorphism
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A
person at the same time can have different characteristics. A man at the same time is a
father, a husband, and an employee. So the same person possesses different behavior in
different situations. This is called polymorphism. An operation may exhibit different
behaviors in different instances. The behavior depends upon the types of data used in the
operation. C++ supports operator overloading and function overloading.
Operator Overloading: The process of making an operator exhibit different
behaviors in different instances is known as operator overloading.
Function Overloading: Function overloading is using a single function name
to perform different types of tasks. Polymorphism is extensively used in
implementing inheritance.
Example: Suppose we have to write a function to add some integers, sometimes there are
2 integers, and sometimes there are 3 integers. We can write the Addition Method with
the same name having different parameters, the concerned method will be called
according to parameters.
Polymorphism in C++
Inheritance in C++
class GFG {
public:
void call_Function() // function that call print
{
print();
}
void print() // the display function
{
cout << "Printing the Base class Content" << endl;
}
};
class GFG2 : public GFG // GFG2 inherit a publicly
{
public:
void print() // GFG2's display
{
cout << "Printing the Derived class Content"
<< endl;
}
};
int main()
{
GFG geeksforgeeks; // Creating GFG's object
geeksforgeeks.call_Function(); // Calling call_Function
GFG2 geeksforgeeks2; // creating GFG2 object
geeksforgeeks2.call_Function(); // calling call_Function
// for GFG2 object
return 0;
}
Output
Printing the Base class Content
Printing the Base class Content
As we can see, the print() function of the parent class is called even from the derived
class object. To resolve this we use virtual functions.
Message Passing
Objects communicate with one another by sending and receiving information. A message
for an object is a request for the execution of a procedure and therefore will invoke a
function in the receiving object that generates the desired results. Message passing
involves specifying the name of the object, the name of the function, and the information
to be sent.
Related Articles:
Classes and Objects
Inheritance
Access Modifiers
Abstraction
Learn to code easily with our course Coding for Everyone. This course is accessible and
designed for everyone, even if you're new to coding. Start today and join millions on a
journey to improve your skills!
Whether you're preparing for your first job interview or aiming to upskill in this ever-
evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide
top-quality content at affordable prices, all geared towards accelerating your growth in a
time-bound manner. Join the millions we've already empowered, and we're here to do the
same for you. Don't miss out - check it out now!