# Using Objects in C++ - Birds
![](images/headerBirds.png)
[Verano 2016 - Ive]
Up to now we've seen how to use variables to store and manipulate data of certain types and how to structure programs by dividing their tasks into functions. An *object* is an entity that is used in many programming languages to integrate the data and the code that operates on it, simplifying the modification of large programs. In today’s laboratory experience you will use a class called `Bird` to practice some basic skills in C++ to create and manipulate objects.
## Objectives:
1. Create objects from a class.
2. Analyze the declaration of a class to understand how to create and manipulate objects of the class.
3. Practice the creation and manipulation of objects, and the invocation of "setters" and "getters".
## Pre-Lab:
Before arriving to the laboratory you should have:
1. Reviewed the following concepts:
a. the creation of objects of a class.
b. using the "getter" method functions to access the attributes of an object.
c. using the "setter" method functions to modify the attributes of an object.
2. Studied the documentation for the class `Bird` available in the documentation for this project (`objects-birds/doc/en/html/class_bird.html`).
3. Studied the concepts and instructions for the laboratory session.
4. Taken the Pre-Lab quiz available in Moodle.
---
---
## Classes and Objects in C++
An *object* is an entity that contains data and procedures to manipulate them. Similar to how each variable has a *type* of data associated to it, each object has a *class* associated to it, which describes the properties of the the objects: its data (*attributes*), and the procedures that can be used to manipulate its data (*methods*).
It is not necessary to know all of the details about the methods of the object to define and use an object, but you must know how to create it and how to interact with it. The necessary information is available in the class' documentation. Before creating objects of any class, we should familiarize ourselves with its documentation. The documentation indicates, among other things, what entity is trying to be represented in the class, and its interface or methods available to manipulate the objects of the class.
Take a look at the documentation of the `Bird` class which can be found in [this link.](http://ada.uprrp.edu/~ranazario/bird-html/class_bird.html).
### Classes
A class is a description of the data and processes of an object. The class’ declaration establishes the attributes that each of the objects of the class will have, and the methods that it can invoke.
If it isn't specified otherwise, the attributes and methods defined in a class will be private. This means that the variables can only be accessed and changed by the methods of the class (*constructors*, *setters*, and *getters*, among others).
The following is the skeleton of the declaration of a class:
---
```
class ClassName
{
// Declarations
private:
// Declaration of variables or attributes
// and prototype member functions
// that are private for this class
type privateVar
type nameOfPrivateMemFunc(type of the parameters);
public:
// Declarations of attributes
// and prototypes of method functions
// that are public for the entire program
type publicVar;
type nameOfPublicMemFunc(type of the parameters);
};
```
---
You can see the declaration of the `Bird` class in the file `bird.h` included in this laboratory experience's program.
### Objects
An object is an entity that contains data (same as a variable), called its `attributes`, and it also contains procedures, called `method`, that are used to manipulate them. The objects are "instances" of a class that are created in a similar manner as how variables are defined:
`ClassName objectName;`
By creating an object we have available the methods of the class that the object belongs to.
### Methods of a Class
The methods of a class determine the actions that we can take on the objects of that class. The methods are similar to functions in the sense that they can receive parameters and return a result. An elementary way to know the methods of a class is reading the class declaration. For example, the following is a section of the declaration of the class `Bird` in the file `bird.h`.
---
```
class Bird : public QWidget
{
.
.
.
Bird(int , EyeBrowType , QString , QString, QWidget *parent = 0) ;
int getSize() const;
EyeBrowType getEyebrow() const ;
QString getFaceColor() const;
QString getEyeColor() const;
Qt::GlobalColor getColor(QString) const;
void setSize(int) ;
void setEyebrow(EyeBrowType) ;
void setFaceColor(QString) ;
void setEyeColor(QString) ;
.
.
.
};
```
---
Once the object is created, its methods provide the only way to change its attributes, to obtain information about them, or do computations with them. This is why the set of methods is commonly called the *interface*. The methods are the interface between the object’s user and its content.
In general, in each class the prototypes of the methods are defined to construct the objects, and to search, manipulate and store the data. The following is a general format of a method prototype:
`typeReturned methodName(type of the parameters);`
Afterwards, we write the corresponding function to the method in the project's code, starting with a header that includes the name of the class that the function belongs to:
`TypeReturned ClassName::MethodName(parameters)`
We declare public methods within the class so that objects that are instances of a class have permission to access private variables (these are the setters and getters). It's preferred to use private variables and access them through the setters and getters, instead of declaring them public since the object that is associated to these variables would have control over the changes that are made.
To invoke a method we write the name of the object, followed by a period and then the name of the method:
`objectName.methodName(arguments);`
#### Constructors
The first methods of a class that we should understand are the *constructors*. A class can have multiple constructors. One of the constructors will be invoked automatically each time an object of that class is created. In most cases, the constructors are used to initialize the values for the object’s attributes. To create objects of a class, we must know which are the constructors of the class.
In C++, the constructors have the same name as the class. The type returned by these functions is not declared since they do not return any value. Their declaration (included in the definition of the class) is like this:
`methodName(type of the parameters);`
The function header will be like this:
`ClassName::MethodName(parameters)`
The class `Bird` that you will be using in today's session has two constructors (overloaded functions):
`Bird (QWidget *parent=0)`
`Bird (int, EyeBrowType, QString, QString, QWidget *parent=0)`
You can see the declarations of the method prototypes in the declaration of the `Bird` class in the project's `bird.h` file. The documentation can be found in [this link.](http://ada.uprrp.edu/~ranazario/bird-html/class_bird.html) The first constructor, `Bird (QWidget *parent=0)`, is a method that can be invoked with one or no argument. If no argument is used, the function's parameter has a value of 0.
A class' constructor that can be invoked without using an argument is the class' *default constructor*; that is, the constructor that is invoked when we create an object using an instruction like:
`Bird pitirre;`
You can see the implementations of the class `Bird` in the file `bird.cpp`. Note that the first constructor, `Bird (QWidget *parent=0)`, will assign random values to each of the object's attributes. Later on there is a brief explanation for the `randInt` function.
Have a look at the documentation for the second constructor, `Bird (int, EyeBrowType, QString, QString, QWidget *parent=0)`. This function requires four arguments and has a fifth argument that is optional since it has a default value. One way to use this constructor is creating an object like this:
`Bird guaraguao(200, Bird::UPSET, "blue", "red");`
#### Setters (mutators)
Classes provide methods to modify the values of the attributes of an objected that has been created. These methods are called *setters* or *mutators*. Usually, we declare one setter for each attribute that the class has. The `Bird` class has the following setters:
* `void setSize (int)`
* `void setEyebrow (EyeBrowType)`
* `void setFaceColor (QString)`
* `void setEyeColor (QString)`
You can see the method's declarations in Figure 1 and in the `Bird` class declaration in `bird.h`, and the implementation of the some of the methods in `bird.cpp`. The code in the following example creates the object `bobo` of the `Bird` class and then changes its size to 333.
```
Bird bobo;
bobo.setSize(333);
```
#### Getters (accessors)
Classes also provide methods to access (get) the value of the attribute of an object. These methods are called *getters* or *accessors*. We usually declare one getter for each attribute a class has. The `Bird` class has the following getters:
* `int getSize ()`
* `EyeBrowType getEyebrow ()`
* `QString getFaceColor ()`
* `QString getEyeColor ()`
You can see the declarations of the methods in Figure 1 and in the `Bird` class declaration in `bird.h`, and the implementations of some of the methods in `bird.cpp`. The code in the following example creates the object `piolin` of the `Bird` class and prints its size:
```
Bird piolin;
cout << piolin.getSize();
```
#### Other Functions or Methods You will use in this Laboratory Experience
**MainWindow:** The file `mainwindow.h` contains the declaration of a class called `MainWindow`. The objects that are instances of this class will be able to use the overloaded methods
`void MainWindow::addBird(int x, int y, Bird &b)`
`void MainWindow::addBird(Bird &b)`
that will add to the screen a drawing of an object of the `Bird` class that is received as an argument. The code in the following example creates an object `w` of the `MainWindow` class, creates an object `zumbador` of the `Bird` class and adds it in the position (200,200) on the screen `w` using the first method.
```
MainWindow w;
Bird zumbador;
w.addBird(200,200,zumbador);
```
---
![figure1.png](images/figure1.png)
**Figure 1.** Window `w` with the image of the object `zumbador` in the position (200,200).
---
**Important!** It's not enough to just create the `Bird` objects so that these appear on the screen. It's necessary to use one of the `addBird` methods to make the drawing appear on the screen.
**randInt:** The `Bird` class includes the method
`int Bird::randInt(int min, int max)`
to generate random numbers in the range [min, max]. The method `randInt` depends on another function to generate random numbers that require a first element or *seed* to be evaluated. In this project, that first element is generated with the function call `srand(time(NULL)) ;`.
---
---
!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-01.html"
!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-02.html"
!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-03.html"
!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-04.html"
!INCLUDE "../../eip-diagnostic/birds-objects/en/diag-birds-objects-05.html"
---
---
## Laboratory session:
In today's laboratory experience you will use the `Bird` class to practice the creation of objects, accessing and changing its attributes.
### Exercise 1 - Study the `Bird` class
In this exercise you will familiarize yourself with the `Bird` class and with some methods associated with the `MainWindow` class that defines the window where the results are displayed.
#### Instructions:
1. Download the `objects-birds` folder from `Bitbucket` using a terminal, moving to the `Documents/eip` directory, and writing the command `git clone http://bitbucket.org/eip-uprrp/objects-birds`.
2. Load the `Birds` project onto Qt by double clicking on the `Birds.pro` file in the directory `Documents/eip/objects-birds` of your computer. Configure the project.
3. Study the `Bird` class contained in the `bird.h` file. Identify the methods that are constructors, setters and getters.
4. In the `main.cpp` file (in Sources) the `main` function does the following:
a. Creates a Qt object application, called `a`. The only thing you need to know is that thanks to this object we can create a graphical application in Qt and interact with it.
b. Creates an object of the MainWindow class called `w`. This object corresponds to the window that you will see when you run the application.
c. Initializes the seed of Qt's random number generator. As a result of this, the new birds will have random sizes, colors and eyebrows (unless we force them to have specific values).
d. Invokes the method `show()` on the object `w`. This shows the window where the results will be displayed.
e. In programs that don't have a graphical interface, the `main()` function usually ends with the instruction `return 0;`. In this project, the `return a.exec();` instruction is used so that the object `a` takes charge of the application from that moment on.
5. Execute the program by clicking on the green arrow in the left menu on the Qt Creator window. The program should display a blank window.
### Exercise 2 - Create objects of the `Bird` class with certain attributes
In this exercise you will create objects of the `Bird` class using the default constructor and using constructors where you define specific characteristics for the object. You will also practice the use of getters and setters to obtain and assign attributes to the objects.
#### Instructions:
1. Create an object of the `Bird` class called `abelardo` using the default constructor and add it to the `w` window using the method `addBird(int x, int y, Bird b)`. Remember that the method's call should start with the name of the object `w` and a period.
2. Run the program several times and marvel at seeing `abelardo` have different sizes, colors and eyebrows.
3. Use the setters `setSize(int size)`, `setFaceColor(Qstring color)`, `setEyeColor(Qstring color)`, and `setEyebrow(EyeBrowType)` so that `abelardo` looks as in Figure 2 (its size is 200).
---
![figure2.png](images/figure2.png)
**Figure 2.** Abelardo.
---
4. Create another object of class Bird called `piolin` that has a blue face, green eyes and UNI eyebrows invoking the constructor `Bird(int size, EyeBrowType brow, QString faceColor, QString eyeColor, QWidget *parent = 0)`. Its size should be half of `abelardo`'s. Add it to the same window where `abelardo` is being displayed by using `w.addBird(300, 100, piolin)`, to obtain an image like the one in Figure 3
---
![figure3.png](images/figure3.png)
**Figure 3.** Abelardo and Piolin.
---
5. Create two other objects called `juana` and `alondra` that will appear drawn in the coordinates (100, 300) and (300,300) respectively. Create `juana` using the default constructor so that its properties are assigned randomly. Create `alondra` using the other constructor so that you may specify its properties during its creation. `alondra` should have the same size as `juana`, have the same type of eyebrows, and the same eye color. Its face should be white. Add `alondra` and `juana` to the window where `abelardo` and `piolin` are. The window should look similar to the one in Figure 4.
---
![figure4.png](images/figure4.png)
**Figure 4.** Abelardo, Piolin, Juana, and Alondra.
---
6. Run the program several times making sure that `alondra` and `juana` have the same size, eyebrows and eyes.
---
---
## Deliverables
Use "Deliverable" in Moodle to hand in the `main.cpp` file that contains the function calls and changes you made to the program. Remember to use good programming techniques, include the name of the programmers involved, and document your program.
---
---
##References
https://sites.google.com/a/wellesley.edu/wellesley-cs118-spring13/lectures-labs/lab-2