C++ Tutorial: Classes and Objects

July 8th, 2014

In this tutorial, we will be taking an introductory look at object-­oriented programming in C++. Here, we will look at classes and objects and their various components. We will look at the basic types of class operations such as constructors, destructors, setters, and getters. Finally, we will look at the key words private, public, and protected.

At the bottom of this page, you will find code for a complete working program that will demonstrate how objects work. Either copy-paste the code into your own project or download the program files from the Github link.

What is Object-Oriented Programming?

Object-­oriented programming is a programming methodology that focuses on modeling data and functions as objects. By contrast, procedural programming focuses on program execution, statement-­by­-statement. In a way, object­-oriented programming is more abstract while procedural programming is closer to the raw machine instructions.

OOP_PPP (13)

Why learn Object-Oriented Programming?

Object-oriented programming is essential to modern computing. Rather than just focus on getting tasks accomplished, object-oriented programming allows you to build models and relationships that reflect the “real world.”

  • Application Development: Object­-oriented programming is how the majority of apps are made today. It’s essential to game programming and making the kind of apps you might use on your phone or tablet.
  • Top-Down Design: Object­-oriented programming is a good way to design programs in an efficient and intuitive manner. Objects give you a high-­level concept to start with so that you can design first and code later.
  • Code Reusability: Object-­oriented programming is also a good way to encapsulate data and keep components functionally separate from each other. If you create a linked list class for one program, you can easily reuse this code in another program as long as the linked list class is self­-contained, meaning it doesn’t rely on external code to do its job.

What is an Object?

In general, we can think of an object as something with a unique identity. This is true in the “real world” as well as in the software world. A bike, for example, is an object with a unique identity since it occupies a unique location in space and time. Likewise, a variable in a program has a unique location in random-access memory and and execution time. Also, an object, such as a bike, possesses its own set of attributes and behaviors. Attributes may include the brand name, color, and price. Behaviors may include pedal, brake, and change gears.

What_Is_Object (14)

In object-oriented programming, a class is a template for creating objects. The template is a particular set of attributes and behaviors. An object is an instance of a class. Objects implement class attributes as data and class behaviors as functions. Basically, a class is a data type and an object is a variable of that class.

Class Functions (i.e. Methods)

The functions of classes are called methods. Here are the main types of methods:

Constructors and Destructors

In general, objects have two basic methods: the constructor and the destructor. The constructor is what instantiates the object and allocates dynamic memory as needed. A constructor that takes in parameters is called a normal constructor while an constructor that does not is called a default constructor. A constructor that takes in a reference to another instance of the class is called a copy constructor. The destructor is used to deallocate any dynamic memory used up by the object. The destructor is called at the end of the object’s lifespan or when the program terminates.

OOP_Methods (4)

Setters and Getters

Besides constructors and destructors, objects have two other kinds of methods: setters and getters. A setter is a method that changes the data attributes of an object. For example, setPrice will take a floating-­point number as a parameter and set the price variable to the value passed in. A getter method retrieves the data of an object. A getter doesn’t change an object, but rather, lets you peek inside of it.

OOP_Methods (13)

Access Specifiers

In C++, there are certain key ­words for controlling the access level of the data members and methods of a class:

  • Private means that the class members are only visible to the class itself. Usually, data members are private so that you can only access them through setter and getter methods. (Note: By default, class members are treated as private in C++).
  • Protected means that the class members are only visible to the class and its derived classes. Protected is used in inheritance chains. (We will cover inheritance in the next tutorial in the object-­oriented programming series).
  • Public means that the class members are visible to entities outside the class. Typically, most class methods are public so that they can be called from outside the class.

OOP_PPP (4)

The process of keeping some class attributes private and independent from other code is encapsulation. Encapsulation is a crucial aspect of object-­oriented programming. It keeps code easy to maintain by keeping it self-­contained. It also enables greater app security by constraining data to only where it is needed.

Coding Example

Below is everything you need to make a working program example. Simply copy and paste the code you need into your own project files or else download the project files from the Github link here.

For simplicity, you could declare and define the Bike class inside main.cpp. First, copy and paste everything in Bike.h between #define Bike_h and #endif into main.cpp outside the main function. Next, copy and paste everything in Bike.cpp into main.cpp outside of the main function. For starting out, consolidating the class declaration, definition, and implementation into one file is quick and dirty. In the long run, however, it’s better to encapsulate the class definition and declaration into separate files away from main.cpp.

Bike_Class

Bike.h

//*****************************************************************
//  Bike.h
//  Objects_Project
//
//  Created by Karlina Beringer on July 8, 2014.
//
//  This header file contains the Bike class declaration.
//  Bike objects model bicycles in the real world.
//*****************************************************************

#ifndef Bike_h
#define Bike_h

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

class Bike
{
//-----------------------------------------------------------------
// Bike attributes (class members are private by default)
//-----------------------------------------------------------------
private:
    string brand;
    string model;
    double price;
    double speed;

//-----------------------------------------------------------------
// Bike behaviors (a.k.a. methods)
//-----------------------------------------------------------------
public:
    // Default constructor creates a generic Bike object.
    Bike();
    
    // Normal construcor creates a custom Bike object.
    Bike( string brand, string model, double price, double speed );

    // Copy constructor creates Bike object clone.
    Bike( Bike & object );
    
    // Getter returns the brand of the bike object.
    string getBrand();
    
    // Getter returns the model of the Bike object.
    string getModel();
    
    // Getter returns the price of the Bike object.
    double getPrice();
    
    // Getter returns the speed in mph of the Bike object.
    double getSpeed();
    
    // Getter computes the distance covered by the Bike.
    double getDistance( double minutes );
    
    // Getter prints a summary of the Bike object's state.
    void print();
    
    // Setter changes the brand of the Bike object.
    void setBrand( string brand );
    
    // Setter changes the model of the Bike object.
    void setModel( string model );
    
    // Setter changes the price of the Bike object.
    void setPrice( double price );
    
    // Setter changes the speed of the Bike object.
    void setSpeed( double speed );
    
    // Destructor is called when the program terminates.
    ~Bike();
};


#endif

//*****************************************************************
// End of File
//*****************************************************************

Bike.cpp

//*****************************************************************
//  Bike.cpp
//  Objects_Project
//
//  Created by Karlina Beringer on July 8, 2014.
//
//  This source file contains the Bike class definition.
//  Bike objects model bicycles in the real world.
//*****************************************************************

#include "Bike.h"

// Default constructor creates a generic Bike object.
// The double colons are called the "resolution specifier."
Bike::Bike()
{
    brand = "brand";
    model = "model";
    price = 0.0;
    speed = 0.0;
}

// Normal constructor creates a generic Bike object.
// Keyword "this" points to the instance calling the method.
Bike::Bike( string brand, string model, double price, double speed )
{
    this -> brand = brand;
    this -> model = model;
    this -> price = price;
    this -> speed = speed;
}

// Copy constructor creates Bike object clone.
// The "dot operator" returns an attribute of the object.
Bike::Bike( Bike & object )
{
    this -> brand = object.brand;
    this -> model = object.model;
    this -> price = object.price;
    this -> speed = object.speed;
}

// Getter returns the brand of the Bike object.
string Bike::getBrand()
{
    return brand;
}

// Getter returns the model of the Bike object.
string Bike::getModel()
{
    return model;
}

// Getter returns the price of the Bike object.
double Bike::getPrice()
{
    return price;
}

// Getter returns the speed in mph of the Bike object.
double Bike::getSpeed() 
{
    return speed;
}

// Getter computer the distance covered by the Bike.
// Distance = Speed * Time
// Miles = (Miles/Hour)*(Minutes)*(Hour/60 Minutes)
double Bike::getDistance( double minutes )
{
    return speed * (minutes/60);
}

// Getter prints a summary of the Bike object's state.
void Bike::print()
{
    cout << "nnBrand:t" << brand << endl;
    cout << "Model:t" << model << endl;
    cout << "Price:t$" << setprecision(2) << fixed << price << endl;
    cout << "Speed:t" << setprecision(4) << speed << " miles per hour" << endl;
}

// Setter changes the brand of the Bike object.
void Bike::setBrand( string brand ) 
{
    this -> brand = brand;
}

// Setter changes the model of the Bike object.
void Bike::setModel( string model )
{
    this -> model = model;
}

// Setter changes the price of the Bike object.
void Bike::setPrice( double price )
{
    this -> price = price;
}

// Setter changes the speed of the Bike object.
void Bike::setSpeed( double speed )
{
    this -> speed = speed;
}

// Destructor is called when the program terminates.
Bike::~Bike()
{
    cout << "Deleting Bike object..." << endl;
}

//*****************************************************************
// End of File
//*****************************************************************

main.cpp

//*****************************************************************
//  main.cpp
//  Objects_Project
//
//  Created by Karlina Beringer on July 8, 2014.
//
//  This file contains the main function of the program.
//  Main implements objects of the Bike class.
//  Bike objects model bicycles in the real world.
//*****************************************************************

// Include the header file for the Bike class.
#include "Bike.h"

int main()
{
    cout << "Starting program...nn";
    
    // Create two Bike objects.
    // Bike is a data type. A and B are Bike variables.
    // A uses the default constructor.
    // B uses the normal constructor.
    cout << "Creating Bike objects A and B...n";
    Bike A;
    Bike B( "Magna", "Glacier Point", 120, 5 );
    
    // Display contents of each Bike objects.
    cout << "Displaying contents of Bike object A...n";
    A.print();
    cout << "Displaying contents of Bike object B...n";
    B.print();
    
    // Set the speed of A to 10 miles per hour.
    cout << "nSetting the speed of A to 10 mph...n";
    A.setSpeed( 10 );
    cout << "Bike A now travels at " << A.getSpeed() << " mph.n";
    
    // Show how far A travels in 15 minutes.
    cout << "In 15 minutes, Bike A travels ";
    cout << A.getDistance( 15 ) << " miles.nn";
    
    // Create a copy of Bike object B name C.
    cout << "Create a copy of Bike object B named C...n";
    Bike C( B );
    cout << "Displaying contents of copy of C...";
    C.print();
    
    // Terminate program.
    cout << "nEnding program...n";
    return 0;
}

//*****************************************************************
// End of File
//*****************************************************************

Program_Output.txt

Starting program...

Creating Bike objects A and B...
Displaying contents of Bike object A...


Brand:	brand
Model:	model
Price:	$0.00
Speed:	0.0000 miles per hour
Displaying contents of Bike object B...


Brand:	Magna
Model:	Glacier Point
Price:	$120.00
Speed:	5.0000 miles per hour

Setting the speed of A to 10 mph...
Bike A now travels at 10.0000 mph.
In 15 minutes, Bike A travels 2.5000 miles.

Displaying contents of copy of C...

Brand:	Magna
Model:	Glacier Point
Price:	$120.00
Speed:	5.0000 miles per hour

Ending program...
Deleting Bike object...
Deleting Bike object...
Deleting Bike object...
Program ended with exit code: 0

References

  1. Carrano, Frank. Timothy, Henry. Data Abstraction & Problem Solving with C : Walls and Mirrors. Boston: Pearson, 2013. Print.
  2. “Classes (I).” cplusplus.com. 2014. http://www.cplusplus.com/doc/tutorial/classes/
  3. “Lesson: Object-Oriented Programming Concepts.” The Java Tutorials. Oracle. 2014. http://docs.oracle.com/javase/tutorial/java/concepts/

Categories: mathtechnologytutorials