C++ Tutorial #1 - Level: 4 - Intermediate:


Introduction
By the time you are done reading this, you will hopefully have an understanding of what a class is, and how it can be used. I am taking this opportunity to familiarize myself with them as well.

First off, you hopefully already have a clear understanding of the basic programming structures, the syntax of C++, and how to create, build, and compile your code. With that being said, we shall move on to the article.

Object Oriented Programming
I am going to use a can of soda as an analogy here. You can imagine it being whatever your favorite is, but for me it is going to be Mug Root Beer. :)

In C++, you have the option of programming in a manner called Object Oriented Programming (OOP), which some people refer to by the pronunciation of its acronym as if it were a word. An object is simply, well, an object! It is a bit of code that can be used to simplify, segment, and take more control over the development of your code. In our analogy, the can of soda will represent our object.

Objects have to start somewhere in the code, much like my can of Mug does in the bottling facility. First, you have to start with a definition of your object, which in C++ is usually done in what is known as a header file. Before we go into that though, lets talk more about what an object is.

Objects, like a can of soda, have different characteristics about them, which we refer to in the programming world as properties. These properties can be almost anything, depending on how you decide to structure your object. With a can of soda, some of your properties are color, flavor, sugar content, and bottle date. Some of the properties can be classified as public properties, while others can be classified as private properties. This classification simply refers to what part of your program has access to what information; with a can of soda, it can be something such as operator number, batch number, or even which bottling facility packaged it. With a program, it depends on how you have structured it.

Classes
Now we need to define what a class is and how it relates to an object. The can of soda had to start somewhere, right? Well, in a program our objects have to start somewhere as well. A class is basically a definition of an object. It contains all the information about the properties and methods, which will be inherited by our object. Inheritance is a big buzzword with OOP. Basically all it means is that anything that is defined in a class will be inherited by the objects created from it.

Now that we have a general idea of objects and classes, we need to start hashing out some code. Don’t worry though, as long as you pay attention and know the general idea of C++, you will have no problem understanding this.

Classes are easiest contained in a header file. Microsoft Visual Studio has an option to create a header file, just the same way that you create a .cpp file with it. To begin working with our class, we need one of these header files to be created. You can also do it with notepad, by saving the file as [filename].h
For simplicity, I will be using notepad to create my header file.

Ok, I now have a file on my desktop called sodaCan.h, which I will be using to keep all my class code in. The very first thing that we need to do, for professionalism and future reference, is create a few comments describing what this header file is all about.



sodaCan.h

// sodaCan.h - Used for the sodaCan object
// Author: Tim Garrison
// Date: 04.28.2003
//----------------------------------------


// Include section
#include <string>
using namespace std;

// Declaration Section
class sodaCan
{
//Public properties and methods
public:
sodaCan(); //Used to create our object
void fillSodaCan(string, float, string);
string getBottlerName();
float volume;
string flavor;


//Private properties and methods
private:
string bottlerName;

}; //End Class

// Implementation Section
sodaCan::sodaCan()
{
volume = 0.0;
flavor = "";
bottlerName = "";
} //end of default constructor

void sodaCan::fillSodaCan(string bottName, float fillVolume, string bottleFlavor)
{
// Assign values to object
volume = fillVolume;
bottlerName = bottName;
flavor = bottleFlavor;
}

string sodaCan::getBottlerName()
{
return bottlerName;
}


Don’t freak out over that now, it is actually quite simple if we break it down. If you look at the very top portion of the code, the declarations and includes section, you will see that it is no different than a regular declaration or include in a .cpp file, with the exception of public and private declarations. If you remember back to the 6th paragraph, you know what the difference between public and private properties and methods is. It simply defines what portions of code have control over what methods and properties.

Next, we move into our implementation section. In this section, we have what is known as a default constructor, which will be used to construct our object. These blocks of code are basically just functions that are tied to the class that is going to be the definition for our object. The way the are tied is through the use of the scope resolution operator, which is just a double colon (::). As you may have already noticed, most of your programs, if not all, contain the use of the using namespace std; statement. This statement is used to eliminate the use of the scope resolution operator in our code for the cout, endl, cin, and many other statements. If we did not have the using namespace std; statement in our code, for each time we wanted to print, get input, or use endl, we would have to type std:: before each one.

Example of std::

std::cout << “Hello world!” << std::endl;
std::cout << “Please enter your name:”;
std::cin >> username;



Isn’t that just nasty looking? It makes life so much simpler by typing those three words at the beginning of the code. But why do we use those? What is their function? As put by Jesse Liberty in the book, Teach Yourself C++ in 21 Days, it is just to tell the compiler that we’ll be using the entire namespace standard; that is, any object not otherwise designated can be assumed to be from the standard namespace. But, since this is the definition of our class, we must use the scope resolution operator.

In our default constructor, we simply initialize our variables, much the same way you would initialize variables upon declaration in a normal .cpp file. This time, however, we do not need to include a data type or give it a name. That has already been done for us in our declaration section, so we just need to give the variables their initial values.

Next, we move into our class’ methods. It is a good idea to put your public methods first, then your private methods. This will make it easier for you to work with them. Again, we need to link our methods to our class through the use of the scope resolution operator. Other than the use of the scope resolution operator, coding the methods will be the same as a .cpp file.

Creating Objects from Classes
Now it is time to get into the fun part of this mess: creating an object from the class we just defined.

sodaCan.cpp

// sodaCan.cpp - Used for the sodaCan object
// Author: Tim Garrison
// Date: 04.28.2003
//----------------------------------------

#include <iostream>
#include <string.h>
#include "sodaCan.h" //Include the class definition

using namespace std;

sodaCan myCan; //Create the object from the class

int main()
{
//Local variables
string bottlerName = "";
string bottleFlavor = "";
float fillVolume = 0.0;

//Get the object properties from the user
cout << "Please enter the bottler's name: ";
cin >> bottlerName;
cout <<"Please enter the flavor for the can: ";
cin >> bottleFlavor;
cout << "Pleae enter the fill volume in fluid ounces: ";
cin >> fillVolume;

//Fill the soda can
myCan.fillSodaCan(bottlerName, fillVolume, bottleFlavor);

cout << endl << endl;

//Display the properties of our can
cout << "Can flavor: " << myCan.flavor << endl;
cout << "Fill volume: " << myCan.volume << endl;

//Display a private property of the can
cout << "Bottler name: " << myCan.getBottlerName() << endl;

return 0; //End of the program
}


Starting out in our includes section, you will notice an entry for our header file, sodaCan.h. This entry may look a little different than most to many people who read this, but the difference is quite simple to explain. First you have the presence of quotes rather than angle brackets. This simply tells the compiler to look in the path specified within the quotes for the file specified. This path is a relative path, but you can specify absolute paths if you have certain header files in certain locations. Second, you will notice that we have put the full filename of our header file, sodaCan.h. This is actually no different than what we have been doing with our includes. The files we have been including before have had no file extension, thus, they do not require one to be specified.

To create our object from the class, we must treat it like any other variable, giving it a data type and a name. We will not give it an initial value here though, because that is done in the default constructor in the .h file. When you declare the object like we are doing in sodaCan.cpp, it executes the code of the default constructor, which initializes the variables and anything else you code into it. In this case, I have declared the object as a global object, meaning that all portions of sodaCan.cpp can access it.

Now, the rest of the code is going to be normal, just like any C++ code, with the exception of assigning variables and such. To assign our variables, we use the sodaCan::fillBottle() method, only we use our object name followed by a dot in place of the sodaCan::. That is where the myCan.fillBottle(… is. Now, to retrieve our properties from the object, such as the flavor and fill volume, we can treat them like variables. If you wanted to print out the flavor, like we did in our code, it would look something like the example below.

Example of printing a property

cout << myCan.volume << endl;



This will print the contents of the volume property, which, if you remember back to sodaCan.h, is a floating-point integer.

You will notice that we are using a function to print our private property of the object. This is because anything outside of sodaCan.h cannot access that property. To solve this, we created the getBottlerName() method as a public method of sodaCan.h

We are printing directly from this method because it returns a string. You could also create a local string variable to hold what is returned from this method. The code would look like the following example.


Example of using a local variable with an object’s method

myString = myCan.getBottlerName();
cout << myString << endl;



Other than that, there isn’t much more to objects and classes. I suppose you could go further in-depth with them, creating objects within objects, but that really depends on the needs of your application. One thing you will need to remember is that in your class file, you must link the methods to the class through the use of the scope resolution operator. If you don’t you will find yourself trying to sort out all kinds of compile time errors. I know from experience. :)