Class


Object

An object in programming represents an object in the physical world of humans and has a set of properties that allows describing this object. Additionally, an object has functions or methods that can be used in it or other objects. For instance, an object of the box type can be destroyed, filled, emptied, etc.
Un objeto en programación representa un objeto en el mundo físico de los humanos y contiene un conjunto de propiedades que permiten describir este objeto. Adicionalmente, un objeto tiene funciones o métodos que operan sobre él o sobre otros objetos. Por ejemplo, un objeto del tipo caja puede ser destruido, llenado, vaciado, etc.

Class

The class keyword is used to define a class in Object-Oriented Programming. In the code below, the Box class is defined. The use of the class keyword in C++, Java and C# is very similar. A class defines an object by describing its properties and behavior. Once a class has been defined, it is possible to create as many object of this class as necessary. A class is similar to a recipe or a process list description to build something.
La palabra clave class es usada para definir una clase en Programación Orientada a Objetos. En el código de abajo, la clase Box es definida. El uso de la palabra clave class en C++, Java y C# es muy similar. Una clase define un objeto describiendo sus propiedades y su comportamiento. Una vez que una clase se ha definido, es posible crear la cantidad de objetos de esta clase que se necesite. Una clase es semejante a una receta o lista descriptiva de un proceso para construir algo.

Box.h
class Box
{
public:
     Box();
     ~Box();
     int width;
     int height;
     int depth;
};

Box.cpp
Box::Box()
{
     width = 0;
     height = 0;
     depth = 0;
}

Box::~Box()
{
}


Tip
When giving a name to a class do not use the plural of the noun. Car is a good name for class, and Cars is not.
Cuando le dé nombre a una clase no use nombres en plural. Carro es buen nombre para una clase, y Carros no lo es.

Tip
First letter of class name must be uppercase. When creating a variable of this class, however, the first letter of the variable must be lowercase, as shown in the example below.
La primera letra del nombre de una clase debe ser mayúscula. Cuando se crea una variable de esta clase, sin embargo, la primera letra de la variable debe ser minúscula como se muestra en el ejemplo de abajo.

Program.h
Book book;
Car myCar;


Tip
A class in C++ is typically organized in two files. In the previous example the Box class is defined in the files: Box.h and Box.cpp. In Java and C# a class is defined in one single file, Box.java or Box.cs respectively. It is very important to note that the filename and the class name SHOULD be the same.
Una clase en C++ es típicamente organizada en dos archivos. En el ejemplo previo la clase Box está definida en los archivos: Box.h y Box.cpp. En Java y C# una clase está definida en un sólo archivo, Box.java o Box.cs respectivamente. Es muy importante observar que el nombre del archivo y de la clase debe ser el mismo.

The Constructor and the Destructor

A class in C++ requires at least two functions: the constructor and the destructor. The constructor is a function that is called when an object of the class is created. The destructor is a function that is called when an object of a class is destroyed. The name of the constructor is the same as the name of the class. The name of the destructor is a tilde follow by the name of the class. For instance, in the Box class of the previous example, the constructor is Box(), and the destructor is ~Box(). The destructor is not necessary in Java and C# because of the way these languages destroy objects; when an object is not longer used it is a candidate to be eventually destroyed, but it cannot be assumed in which moment the object will be destroyed. The animation below shows when the constructor and destructor are executed.
Una clase en C++ requiere de al menos dos funciones: el constructor y el destructor. El constructor es una función que se llama cuando un objeto de la clase se crea. El destructor es una función que se llama cuando un objeto de la clase se destruye. El nombre del constructor es el mismo que el nombre de la clase. El nombre del destructor es una tilde seguido del nombre de la clase. Por ejemplo, en la clase Box del ejemplo previo, el constructor es Box(), y el destructor es ~Box(). El destructor no es necesario en Java ni en C# debido a la forma en que estos lenguajes destruyen los objetos; cuando un objeto ya no se usa éste es candidato para ser eventualmente destruido, pero no se puede asumir en que momento se destruirá. La animación de abajo muestra cuando se ejecutan el constructor y el destructor.

Constructor

Class Wizard

Microsoft Visual Studio includes a wizard to create the file or files required for a class. To add a C++ class: Project > Add Class...> Visual C++ > C++ > C++ class . If you do not want to use the wizard, you may create the file(s) manually. If you want to delete a class, you may remove the class file(s) from the project; you may optionally delete the class file or files.
Microsoft Visual Studio incluye un asistente para crear el archivo o archivos requeridos para una clase. Para agregar una clase en C++: Project > Add Class...> Visual C++ > C++ > C++ class . Si usted no quiere usar el asistente, usted puede crear el archivo(s) manualmente. Si usted quiere eliminar una clase, usted puede remover el archivo o archivos de la clase del proyecto; usted puede opcionalmente eliminar el archivo o archivos de la clase.

Tip
A class is very similar to a structure in structured programming. As matter of fact, a structure and a set of functions that take this structure as argument are the version of a class in structured programming.
Una clase es muy similar a una estructura en programación estructurada. De hecho, una estructura y un conjunto de funciones que toman esta estructura como argumento son la versión de una clase en la programación estructurada.

class versus structure

The main differences between a class and a structure are depicted in the table below.
Las principales diferencias entre una clase y una estructura son mostradas en la tabla de abajo.

Feature    structure    class  
Variables to store propertiesYesYes
ConstructorNoYes
DestructorNoYes
Keywords to protect data integrityNoYes
Public functions to operate the objectNoYes
Private functions to maintain the objectNoYes
Functions that can be executed by specific objectsNoYes

Característica    estructura    clase  
Variables para almacenar propiedadesYesYes
ConstructorNoYes
DestructorNoYes
Protección de la integridad de los datosNoYes
Funciones públicas para operar el objetoNoYes
Funciones privadas para mantener el objetoNoYes
Funciones que pueden ser ejecutadas por ciertos objetosNoYes

Tip
A class defines a new data type, which can be used to create objects of this type. A class is the description of an object. For instance, once a box of CDs has been defined, it is possible to create objects of this class. Each box of CDs in the world was created following the specification in the class definition. In the same way, the behavior of this box follows the behavior defined in the class of this box.
Una clase define un nuevo tipo de datos, el cual puede usarse para construir objetos de ese tipo. Una clase es una descripción de un objeto. Por ejemplo, una vez definido la clase caja de CDs es posible construir objetos de esta clase. Cada caja de CDs que hay en el mundo fue creada siguiendo la especificación en la definición de la clase. En la misma forma, el comportamiento de la caja sigue el comportamiento definido en la clase de esta caja.

Problem 1
Make a list of properties and functions of a Cellphone class that defines cell phones. List at least five properties and at least five functions.
Haga una lista de propiedades y funciones de una clase Cellphone que define teléfonos celulares. Liste al menos cinco propiedades y al menos cinco funciones.

Problem 2
(a) Which are the differences between creating a cell phone from the brand Nokia, and creating one from the brand Samsung? (b) Which are the differences between destroying a Nokia cell phone, and destroying a Samsung cell phone?
(a) Discuta cuales son las diferencias entre construir un teléfono celular Nokia y uno Samsung. (b) Discuta cuales son las diferencias entre destruir un teléfono celular Nokia y uno Samsung.

Tip
The code below shows a typical example using structured programming.
El código de abajo muestra un ejemplo típico usando la programación estructurada.

Program.c
struct Box
{
     int width;
     int height;
     int depth;
};

void Initialize(Box* box)
{
     box->width = 0;
     box->height = 0;
     box->depth = 0;
}

void Inflate(Box* box, int amount)
{
     box->width += amount;
     box->height += amount;
     box->depth += amount;
}

void Main()
{
     Box box;
     Initialize(&box);
     Inflate(&box, 20);
}


Tip
The following files provide the OOP version of the previous example.
Los archivos siguientes proporcionan la versión POO del ejemplo previo.

Box.h
class Box
{
public:
     Box();
     ~Box();
     int width;
     int height;
     int depth;
     void Inflate(int amount)
};

Box.cpp
Box::Box()
{
     width = 0;
     height = 0;
     depth = 0;
}

Box::~Box()
{
}

void Box::Inflate(int amount)
{
     width += amount;
     height += amount;
     depth += amount;
}

Program.cpp
#include "Box.h"
void Main()
{
     Box box;
     box.Inflate(20);
}

Problem 3
Compare the two previous examples and list some advantages of using OOP vs. structured programming.
Compare los dos ejemplos previos y liste algunas ventajas de usar la Programación Orientada a Objetos contra la programación estructurada.

Tip
In structured programming, there is a set of global functions while in OOP each object has its own functions.
En la programación estructurada hay un conjunto global de funciones mientras que en la programación orientada a objetos cada objeto tiene sus propias funciones.

Tip
In OOP, the programmer can focus on designing and creating a class. In structured programming, the programmer cannot focus very specifically in each part of the program because the parts of the program are not clearly defined.
En la Programación Orientada a Objetos, el programador puede concentrarse en diseñar y crear una clase. En programación estructurada, el programador no puede enfocarse muy específicamente en cada parte del programa porque las partes del programa no están claramente definidas.

Tip
In OOP, each programmer can work on the design and implementation of a class. Classes can be integrated later in a bigger project.
En la Programación Orientada a Objetos, cada programador puede trabajar en el diseño e implementación de una clase. Las clases pueden ser integradas después en un proyecto más grande.

Problem 4
Create a Wintempla Dialog application called Library and use the Add Class Wizard to add the Book class. Edit the Book.h and Book.cpp files as shown. Remember that the Wizard only creates the two class files: Book.h and Book.cpp.
Cree una aplicación Wintempla de Diálogo llamada Library y use el asistente de Add Class para agregar la clase Book. Edite los archivos Book.h y Book.cpp. Recuerde que el Asistente solamente crea los dos archivos de la clase: Book.h y Book.cpp.

AddClass

BookClass

Book.h
#pragma once
class Book
{
public:
     Book(void);
     ~Book(void);
     COLORREF color;
     int numbPages;
     wstring author;
     int year;
     double price;
};

Book.cpp
#include "StdAfx.h"
#include "Book.h"


Book::Book(void)
{
     color = RGB(0, 0, 0); // Default is black
     numbPages = 0;
     //author
     year = 1990;
     price = 0.0;
}


Book::~Book(void)
{
}

Problem 5
Check that the Book class is displayed in Class View. To open the Book.h file double click in the name of the class in Class View. To open the Book.cpp file double click in any of the function of the class. Class View provides a quickest navigations inside a project than Solution Explorer (File View). Try to always use Class View to edit your project code.
Verifique que la clase Book aparece en la vista de Clases. Para abrir el archivo Book.h haga doble click en Class View en el nombre de la clase. Para abrir el archivo Book.cpp haga doble click en las funciones dentro de la clase. Class View permite navegar más rapidamente dentro de un proyecto que Solution Explorer (File View). Siempre trate de usar Class View para editar el código de su proyecto.

ClassView

Problem 6
Debug the program and use the Watch to check the value of the only Book object.
Depure el programa y use el Observador (Watch) para verificar el valor del único objeto Book.

Library.cpp
#include "stdafx.h" //________________________________________ Library.cpp
#include "Library.h"
#include "Book.h"

int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE , LPTSTR cmdLine, int cmdShow){
     Library app;
     return app.BeginDialog(IDI_LIBRARY, hInstance);
}

void Library::Window_Open(Win::Event& e)
{
     Book book;
     book.price = 198.50;
     book.numbPages = 220;
     book.author = L"Edgar Alan";
     book.color = RGB(0, 0, 200); // Blue
}

Debug1

Debug2

Debug3

Debug4

Tip
You must end your class declaration with a semicolon as shown in the code below.
Usted debe terminar la declaración de su clase con un punto y coma tal como se muestra en el código de abajo.

Semicolon

Tip
The program below shows how to create an object of the Box class. The main difference between how to declare a variable in C++ and Java, is that in Java the new operator is used to create a new box and the reference called box makes reference to this new box (in an incorrect way it can be said that box points to the new box), while in C++ the box variable is a variable of the Box Class.
El programa de abajo muestra cómo crear un objeto de la clase Box. La principal diferencia entre declarar una variable en C++ y Java es que en Java se usa el operador de new para crear la caja y la referencia que se llama box hace referencia a esta nueva caja (en forma incorrecta se puede decir que box apunta a la nueva caja que se creó), mientras que C++ la variable box es una variable de la clase Box.

Program.cpp
class Program
{
public:
     Program()
     {
          Box box;
     }
};


Program.java
public class Program
{
     public Program()
     {
          Box box = new Box(); // box is a reference to a new box
     }
};


Tip
In C++ a local variable is destroyed when the function ends or returns. In C++ a member variable is destroyed when the object is destroyed. In Java a local variable or a member variable is destroyed when the garbage collector performs the deletion because there is not more memory or following a release memory mechanism. If you want the Java garbage collector to destroy an object, you must set the reference of this object to null; note that object destruction is not immediate.
En C++ una variable local es destruida cuando la función regresa o termina. En C++ una variable miembro es destruida cuando el objeto se destruye. En Java una variable local o una variable miembro es destruida cuando el recolector de basura lo haga porque ya no hay suficiente memoria o siguiendo un mecanismo de liberación de memoria. Si usted quiere que el recolector de basura en Java destruya un objeto, usted debe fijar la referencia de este objeto a null; note que la destrucción del objeto no es inmediata.

© Copyright 2000-2021 Wintempla selo. All Rights Reserved. Jul 22 2021. Home