In our last two articles, we gave a brief introduction to object-oriented programming, particularly classes and objects – we explained properties and methods, and mentioned constructors. Now we will further explain these things with code examples in C++. (The syntax for these basic things like defining classes and initializing objects is similar in other object-oriented languages like Java and C#.)
Let’s create a simple class to model a city:
Some of the lines above are pretty self-explanatory: there is data in the form of fields, and one method which returns the number of residents of our city. The data types we used are string (this time, we have a built-in
string class), integer and bool - all of which are familiar from our C tutorial. The
public keyword is a so-called access modifier, and it determines whether certain data from the class is "visible" (and who it's visible to), i.e. it allows or forbids access to the data (to objects of different classes, for example). Other access modifiers in C++ are
private, but we will discuss access modifiers in greater detail later.
Note: This is a trivial example of a class. It's very simple and uses just a few fields to give you an example. Usually, classes are much more complex, and they are the building blocks of your program. It is important to construct your class intelligently, in a way that will allow you to easily modify and upgrade it in the future.
Now, let's see how we can create objects of the class.
The most common way is just writing:
are objects of our
class. You can also write that like this:
City city1, city2;
Now, let's assign some real values to one of our objects, for example:
city1.name = "Paris";
city1.numberOfPpl = 2000000;
city1.isCapital = true;
city1.country = "France";
Now, we can use that data like this:
cout << "The number of people in Paris is: " << city1.numberOfPpl;
or like this (the two ways are equivalent in our case, since the
method returns the
cout << "The number of people in Paris is: " << city1.population();
cout << part is writing the output (in our case, 2000000) to the console.
cout is a method similar in its purpose to C's
printf function we already used.
As we said, this is one way of creating objects in C++. These are automatic objects, which are going to be destroyed (by a special method called the destructor) upon exiting the current scope. There are other ways of creating objects, and one of them is dynamically, using the keyword
new. We will discuss this method in a future post, as it requires a deeper understanding of OOP methodology.