Back in lesson 1.3 -- Introduction to variables, we defined an object
in C++ as, “a piece of memory that can be used to store values”. An object
with a name is called a variable
.
In “traditional programming” (what we’ve been doing up to this point), programs are basically lists of instructions to the computer that define objects and then manipulate those objects (typically via functions). The objects and the functions that work on those objects are separate entities that are then combined together to produce the desired result.
Consider the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> struct Fraction { int numerator; int denominator; }; // Here's a function that prints a Fraction void printFraction(const Fraction &f) { std::cout << f.numerator << "/" << f.denominator; } int main() { // Here is the object that represents a Fraction Fraction f { 2, 5 }; // We connect the behavior (printFraction) to the data (f) to achieve the desired result printFraction(f); return 0; } |
In the above program, the function that prints a Fraction is separate from the Fraction itself, connected only via the Fraction input parameter.
Objects in real life
Take a look around you -- everywhere you look are objects: books and buildings and food and even you. Objects have two major components to them: 1) A list of relevant properties (e.g. weight, color, size, solidity, shape, etc…), and 2) Some number of behaviors that they can exhibit (e.g. making a noise, moving to a new location, etc…). These properties and behaviors are inseparable. A person has a weight and a size, a cat meows, etc…
The struct objects we’ve been defining in our programs already have properties. Consider the Fraction struct above, it defines some properties (the members id
, age
, and wage
), which we can access through the member selection operator (operator .)
. However, these objects are deficient in that they don’t have any associated behaviors.
Intro to class type objects and member functions
C++ provides us with the ability to create objects that tie together both properties and behaviors into a self-contained, reusable package. These objects that contain both properties and behaviors are called class type objects, or often just classes. Classes form the cornerstone of object-oriented programming, which you’ve probably heard of (but if not, that’s okay too).
As an aside...
The word object
is often used ambiguously in C++. In traditional programming, an object is a piece of memory that can be used to store values. In object-oriented programming, an object is a class type object that contains both properties and behaviors.
Most of the time, in C++, when you hear the word “object”, it actually means a class type object, not a traditional programming object.
Wheres properties are implemented as “data members”, behaviors are implemented as “function members” (more often called “member functions”). A member function of a class is a function that is defined as part of the class itself.
1 2 3 4 5 6 7 8 9 |
#include "FractionClass.h" // we're hiding the definition of FractionClass in this header file so we don't have to explain it right now int main() { FractionClass f { 2, 5 }; // instantiate a member of type FractionClass f.printFraction(); // invoke member function printFraction() on object f return 0; } |
As an aside...
If you want a full program that compiles, you can use this one:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include <iostream> // note: This is the simplest version of a Fraction object that compiles and exhibits a member function // This violates many best practices and so is provided only to illustrate a point, not as an example of what good looks like struct FractionClass { // Data members int numerator; int denominator; // Member function void printFraction() { std::cout << numerator << "/" << denominator; } }; int main() { // Here is the object that represents a Fraction FractionClass f{ 2, 5 }; // We invoke the behavior that is part of the data object to achieve the desired result f.printFraction(); return 0; } |
The interesting thing to note here is the printFraction
function. Much like
numerator
and denominator
are data members of the Fraction
struct, the printFraction
function is a member function[def] of our FractionClass. Member functions are essentially just normal functions that are associated with a specific type.
Whereas printFraction() took a Fraction as a parameter (printFraction(f)
), normal member function are invoked via a slightly different syntax (f.printFraction()
).
member functions are invoked on an object, which becomes the implicit subject of that function. Thus, when we say f.print()
, we're saying "call member function print() on object f". It's effectively a different syntax for a similar thing, but it helps make it clear that print() is a member function of whatever type f
is.
Whiel add
While this doesn't seem like a big change, it is, when coupled with a few
Rather than being focused on writing functions, we're focused on defining objects that have a well-defined set of behaviors. This is why the paradigm is called "object-oriented".
This allows programs to be written in a more modular fashion, which makes them easier to write and understand, and also provides a higher degree of code-reusability. These objects also provide a more intuitive way to work with our data by allowing us to define how we interact with the objects, and how they interact with other objects. OOP doesn't replace traditional programming methods. Rather, it gives you additional tools in your programming tool belt to manage complexity when needed.
Note that the term "object" is overloaded a bit, and this causes some amount of confusion. In traditional programming, an object is a piece of memory to store values. And that's it. In object-oriented programming, an "object" implies that it is both an object in the traditional programming sense, and that it combines both properties and behaviors.
[section]Data-only structs are like objects with no behaviors[/section]In the prior lesson, we defined some data-only structs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
struct Employee { short id; int age; double wage; }; int main() { Employee you { 1, 29, 32000 }; std::cout << you.id; // use member selection operator to access property return 0; } |
Note that object you
is an object that has properties (the members id
, age
, and wage
). We use the member selection operator
(operator .) to select a specific member.
All that's missing are the behaviors.
[section]Classes are data-only structs with behaviors[/section]In C++, we typically call objects with behaviors as [def]classes, or class types. Classes have a few notable properties:
1) They can self-initialize to a non-zero value
2) Properties typically aren't accessible directly
3) They have functions (behaviors) that can also be accessed via the member selection operator
.
We'll introduce our first class, std::string
, in the next tutorial, but just as an example:
1 2 3 4 5 6 7 8 9 10 11 |
#include <string> // for std::string #include <iostream> int main() { std::string str { "Hello, world!" }; // initialize a std::string with a string literal std::cout << str; // they can work with existing operators std::cout << ' ' << str.length(); // we use the member selection operator to invoke behaviors return 0; } |
The above prints:
Hello, world! 13
Object-oriented objects in C++ are class types (and thus should generally be passed via reference).
Defining your own objects
Just as you can define your own data-only structs, you can define your own classes. We have many chapters devoted to this topic later in the tutorial series!
For the time being, we'll focus more on using classes.
Using objects
At the beginning of this chapter, we noted that most of the types in the standard library are class types.
![]() |
![]() |
![]() |
Dear all friends,
I am a beginner with C++. Actually it's very difficult for me to complete exercises OPP at the begining. My teacher gave us some exercises. I have tried but not success. So, please help me on these exercises.
Exercise 1:(3Points)
The 10 digit International Standard Book Number(ISBN)is a unique numeric commercial book
identifier developed by the International Organization for Standardization(ISO).It was used until
2007,after which a 13 digit ISBN number was defined.
The 10 digit ISBN consists of 9 identifier digits and one check digit at the end.It is usually written
in the following form
X-XXX-XXXXX-C
where C denotes the check digit. The identifier digits are in the range 0-9,the check digit can be
either in the range 0-9 or be the letter ‚X’.
You should model an ISBN number as a C++ class, therefore:
• Draw a UML class diagram of the ISBN class(model the 9 identifier digits as one single
integer value with nine digits (e.g.0-233-45678 is modeled as the integer 23345678) ,the
check digit as a single character value)
• Declare your modeled ISBN class in C++, including a constructor that takes an integer and a
Character to initialize the corresponding member values, in a file named„ isbn.h“
• Implement the constructor of the class in a file named „isbn.cpp“. The constructor should
Initialize the member values of the object using the given parameter values.
Seehttp://en.wikipedia.org/wiki/ISBN#ISBN10foracloserexplanationoftheISBN10.
Exercise 2:(2Points)
Add a member function
void show () const;
to the ISBN class which prints the whole ISBN number (including check digit) on the screen in the following format:
X-XXX-XXXXX-C
If the number is shorter than 9 digits, fill it up with 0s to the left.
Explain in comments what the keyword„ const“ means in this case (void show () const)and why it is good (or not good) to be used for this function.
Exercise 3:(1Point)
Write a main function in a file called„sheet1.cpp“ which creates three ISBN objects (enter their
ISBN number as integer and check character directly into the C++source, you do not need to read
Them from std::cin) and prints out their numbers in the format shown in exercise 2.
Create a simple Make file and compile the program (consisting of the two.cpp implementation files
As well as the .h header file).Execute your program.
Thank you very much for your help.
Its very nice material..
I have been rather confused by some of the terminology of OOP, such as 'class', and 'wrapper', etc.; however, it appears as though these things are simply evolutions of the old 'subroutine' construct. Using a subroutine is now handled by the language which acts as a 'traffic controller' making it unnecessary for the programmer to keep up with 'returns' and allowing program flow to continue in any direction. If this is the case then it is not so hard to understand.
Does the date at the top of the page tell when you wrote the page and published it?
[ Yes, that is correct. -Alex ]
So object oriented programming can only be done with C++...not java or anything other?
Object oriented programming is available in many of the popular languages today, including Java, C#, Python, Perl, etc...
I'm thrilled after I read this article!! At this moment I'm taking intermediate C++ programming, and soon our teacher will teach us object-oriented programming (hope I'm right). And again, thank you for creating such a great C++ resource for programmers