Skip to main content

Section 16.2 Objects

As we learned while working with strings, objects are entities in code that unite some data (state) and functions that work on that data (behaviors). When other parts of a program’s code are making use of an object, they rely on those functions to work with object and manipulate its state.
You can think of an object as being like a struct that has built in functions. To understand how objects are different than structs, let’s start by comparing procedural code that we might write to define and work with a Point struct with the object-oriented code we would write for a Point object.
Below the two approaches are presented side by side. Don’t worry about trying to understand all of the code. For now, just note some key differences. We will learn about why the code is different in the next few sections.
  • We have a class Point instead of a struct Point. (line 7)
  • The keywords public and private appear in the class. (lines 8, 11)
  • The member variables x and y have been renamed m_x and m_y (line 9).
  • The functions are defined inside of the class. (The class does not end until line 32).
  • The createPoint function is now just called Point. And it lacks a return type! (line 13)
  • The shift and toString functions do not take a Point parameter (lines 19 and 26).
  • The code that is using the Point (the main function), calls functions on a particular point instead of passing points as parameters. It is p1.toString instead of toString(p1). (line 36).
Listing 16.2.1. Struct vs. Class

Note 16.2.1.

In truth, C++ structs are much more similar to classes than we are describing in this chapter. Everything that can be done with classes can be done with structs as well. The only major difference is that struct members are public by default while class members are private.
We are intentionally only using the basic features of structs to emphasize the conceptual differences between procedural programming and object oriented programming.

Checkpoint 16.2.1.

You have attempted of activities on this page.