Blog School of Programming C++ Classes Explained

C++ Classes Explained

C++ likely would not exist without classes. As the original C programming language grew more decipherable, C++ was born. Because C++ was built entirely with objects in mind, C++ uses classes to make it easy to work with objects. Classes and objects became the building blocks C++ uses for creating streamlined and easy-to-read code.

What exactly is a C++ class, and how does it tie into making it easy to use, follow and compile code? We’re glad you asked.

What Is a C++ Class?

A C++ class is an outline the programming language uses to create objects (more on those in a bit). It’s a user-defined source of information that a program can use to generate output based on the class’s parameters. Because it’s so important to stay organized when writing code, classes are great tools for accomplishing just that. For this reason, C++ programmers learn classes very early on.

In non-programming terms, think of a class as like a blueprint for a room. This blueprint will tell you how tall, wide and long the room needs to be, along with any other information necessary to design the room. From the blueprint’s description, a builder has all the information they need to construct the room. In C++, the room generated from the parameters of the blueprint would be the object.

How To Create a Class

Using C++, you can first define a class using the keyword “class,” followed by a descriptive word that names the class. The class name should start with an uppercase letter. An example is as follows:

class Room {
// class definition
}

The components of the blueprint listed above are the attributes required to create the object and the class-specific functions (methods) that each object of the class will have access to. 

Attributes and methods of a class can be one of three things: public, private, or protected. “Public” means the data in the class can be accessed from outside the class. “Private” is where the data can only be accessed from within the class. Lastly, “protected” behaves like the “private” keyword, but functions and variables can also be accessed by child classes (which pull functions and variables from the parent class).

Our C++ class begins to take shape:

class Room {

  public:
int length;
int width;
int height;
}

We now have length, width, and height parameters for a room. Our blueprint is now coming together!

Now let’s add a few methods for our class. These methods use the attributes that we defined above:

double calculateArea() {
  return length * width;
}

double calculateVolume() {
    return length * width * height;
}

Each object of the Room class will now contain the attributes that we defined as well as have access to the Area and Volume methods.

What Is Object-Oriented Programming?

Object-Oriented Programming, or OOP, is where C++ classes shine the brightest. As opposed to procedural programming, where code with lots of functions and variables often runs the risk of being lengthy and redundant, OOP provides a clear structure for the storage and access management of variables and functions. A single class can logically group code into domain-specific areas. Object-oriented programs keep the code neat, and code execution can be faster as a result.

Why Are Classes Relevant to Object-Oriented Programming?

Object-oriented programming could not exist without classes, as classes are the bread and butter of OOP. Thanks to classes and their ability to give you a logical way to group code and shape it around objects and data, the user or program can reuse the same lines of code within a C++ class to generate the necessary output. The very fact that C++ was built around OOP is one of the main reasons the programming language rose to prominence.

To go one step further, classes allow for the simplification of even some of the most complex systems provided there are logical chunks within the system. The details of a one hundred room house are now much easier to code, as each room will have the same basic parameters that can be called upon from a single class. With classes and OOP, the sky’s the limit!

The code will all be contained in one clean area of the program, making it incredibly easy to change the behavior of a group of objects as needed. Need to make all bedrooms bigger? Find the Room class in your code and adjust the attributes or methods for those bedrooms.

What Is an Object?

We’ve alluded to objects up to this point, so let’s finally take a look at what they are. While classes are the blueprint that allows us to store all our data, an object is the creation of a specific instance of the class. In our earlier example, a house can have several rooms where every room is a different size. We need to start creating rooms from the blueprint in order to have a place to sleep at night.

How To Create an Object

Using the main function, we can define our first bedroom as follows:

int main() {
  // ...
  // create an object called bedroom1 from the Room class
  Room bedroom1;

  // input variables
  bedroom1.length = 50;
  bedroom1.width = 40;
  bedroom1.height = 10;
}

Here, bedroom1 is the name of the object we’ve created. This creates a new Room object and stores it in the bedroom1 variable, which can now be used in other places in our code as needed.

Multiple Objects From a Class

As we alluded earlier, the most beautiful thing about classes is that they can generate multiple objects from a single bit of class code. There’s no need to recreate the class or create a new class; we can use the parameters that we’ve already created to make more objects.

Following the same example: 

Room bedroom2;

Here, we’re creating a second bedroom in our imaginary house by inputting new variables that make up the dimensions of that second room.

Putting the Code to Use

We can then call upon those same variables to output any information that may be pertinent to the program. An example would be:

cout << "Area of Bedroom 2 =  " << bedroom2.calculateArea() << endl;
cout << "Volume of Bedroom 2 =  " << bedroom2.calculateVolume() << endl;

Our program would then use the information in our class with the variables we entered to create outputs.

It goes without saying that we can create the same functions to calculate room area and volume with the second bedroom as well. These generated values can be used anywhere in the program as part of a bigger picture, such as laying out measurements for an entire house.

Just How Far Do Classes Go?

All this begs the question of whether or not data types like int are part of a class in C++. Since int has a set of states and operations, it does function similarly to a class with its values and operations. In a way, it’s possible to think of int as a class whose operations could be thought of as functions.

However, int and other basic types in C++ cannot be inherited and cannot have a method defined at the class level. Although int and class are both C++ data types, they are not classes themselves!

Don’t Wait; Learn C++ Today

C++ is an excellent programming language for beginners and experts alike. Proficiency in C++ is as in-demand as ever. Learning object-oriented programming can get you on the path to writing complex code in an organized, accessible way through the use of C++ classes. With a bit of effort, it can be easy to learn but also has a depth that requires a more involved study to master.

Luckily, our C++ Nanodegree is designed to help you master everything this programming language has to offer. Our interactive course will take you through a series of expert-supervised projects and even includes insights from the father of C++ himself.

Start Learning

Stay updated on the latest in technology

"*" indicates required fields

Stay updated on the Latest in Tech

Be first to hear about special offers, news, and resources from Udacity

"*" indicates required fields