Using Objects in C++ - Birds
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:
- Create objects from a class.
- Analyze the declaration of a class to understand how to create and manipulate objects of the class.
- Practice the creation and manipulation of objects, and the invocation of "setters" and "getters".
Pre-Lab:
Before arriving to the laboratory you should have:
Reviewed the following concepts:
a. The creation of objects of a class.
b. The use of the "getter" method functions to access the attributes of an object.
c. The use of the "setter" method functions to modify the attributes of an object.
Studied the documentation for the class
Bird
available in this link.Studied the concepts and instructions for the laboratory session.
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 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.
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. 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 object 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);
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)) ;
.
Bird
class?
setEyeColor
setFaceColor
getSize
getHeight
getEyebrow
Bird
class, except getHeight
.
Bird
class called piolin
?
Bird instance piolin;
piolin class Bird;
piolin(Bird);
Bird piolin;
Bird::piolin
Bird piolin;
since the Bird
class has a constructor that requires no arguments.
abelardo
is an object of type Bird
, how would you invoke the method getSize
on abelardo
?
getSize.abelardo;
abelardo.getSize();
getSize(abelardo);
abelardo::getsize
Bird::abelardo.getSize()
abelardo.getSize();
. The syntax to invoke a method on an object is: NameOfObject.NameOfMethod(parameters)
.
cotorra
of the Bird
class?
cotorra.setSize(10);
setSize(cotorra,10);
cotorra.setSize() = 10;
cotorra.size = 10
Bird::cotorra.setSize() = 10
cotorra.setSize(10);
. The syntax to invoke a method on an object is: NameOfObject.NameOfMethod(parameters)
. The method setSize()
requires an argument of integer type (that is provided between the parenthesis).
Bird
?
Bird a(200);
Bird b;
Bird c(200, Bird::UPSET, “blue”, “red”);
Bird d(Bird);
Bird::f;
Bird
object passing only one argument. The Bird
class has two constructors: one that does not need to receive arguments and another one that needs to receive four or five arguments. The second option: Bird b;
would invoke the constructor that does not receive arguments. The third option: Bird c(200, Bird::UPSET, “blue”, “red”)
invokes the constructor that receives four of five arguments. The other two options are not valid either.
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:
Load the project
Birds
intoQtCreator
. There are two ways to do this:- Using the virtual machine: Double click the file
Birds.pro
located in the folder/home/eip/labs/objects-birds
of your virtual machine. - Downloading the project’s folder from
Bitbucket
: Use a terminal and write the commandgit clone http:/bitbucket.org/eip-uprrp/objects-birds
to download the folderobjects-birds
fromBitbucket
. Double click the fileBirds.pro
located in the folder that you downloaded to your computer.
- Using the virtual machine: Double click the file
Study the
Bird
class contained in thebird.h
file. Identify the methods that are constructors, setters and getters.In the
main.cpp
file (in Sources) themain
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 objectw
. 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 instructionreturn 0;
. In this project, thereturn a.exec();
instruction is used so that the objecta
takes charge of the application from that moment on.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:
Create an object of the
Bird
class calledabelardo
using the default constructor and add it to thew
window using the methodaddBird(int x, int y, Bird b)
. Remember that the method's call should start with the name of the objectw
and a period.Run the program several times and marvel at seeing
abelardo
have different sizes, colors and eyebrows.Use the setters
setSize(int size)
,setFaceColor(Qstring color)
,setEyeColor(Qstring color)
, andsetEyebrow(EyeBrowType)
so thatabelardo
looks as in Figure 2 (its size is 200).Figure 2. Abelardo.
Create another object of class Bird called
piolin
that has a blue face, green eyes and UNI eyebrows invoking the constructorBird(int size, EyeBrowType brow, QString faceColor, QString eyeColor, QWidget *parent = 0)
. Its size should be half ofabelardo
's. Add it to the same window whereabelardo
is being displayed by usingw.addBird(300, 100, piolin)
, to obtain an image like the one in Figure 3Figure 3. Abelardo and Piolin.
Create two other objects called
juana
andalondra
that will appear drawn in the coordinates (100, 300) and (300,300) respectively. Createjuana
using the default constructor so that its properties are assigned randomly. Createalondra
using the other constructor so that you may specify its properties during its creation.alondra
should have the same size asjuana
, have the same type of eyebrows, and the same eye color. Its face should be white. Addalondra
andjuana
to the window whereabelardo
andpiolin
are. The window should look similar to the one in Figure 4.Figure 4. Abelardo, Piolin, Juana, and Alondra.
Run the program several times making sure that
alondra
andjuana
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