What is Object Oriented Programming?

OK, over the next few weeks we’re going to step back a bit from code and command, and instead take a straightforward look at object oriented programming, or OOP*.

Why?

Because it’s often something that crops up in interviews, and the main concepts are things that all programmers should be able to rattle off and feel comfortable talking about. If you come from a low-level, or even machine-level programming background, it’s still A Good Thing to know what this object oriented lark is all about.

OOP deals with objects

Unfortunately there is no standard definition of “object oriented programming” that everyone agrees on, aside from the fact that it uses objects, which is possibly one of the reasons why so many people use it day in and day out, but have trouble defining or explaining what they are actually doing.

OOP requires a particular way of thinking. Instead of planning out a sequence of instructions in your program, you need to think about what you might want it to do, break it up into useful objects, and then allow those objects to interact with each other. There is no set order or route through the code (although all paths should be testable, but that’s a different subject entirely!).

An analogy I often use is to imagine a room full of people talking to each other. Each person is an object, and each object reacts to what other objects around them are saying.

How is OOP implemented?

An object is a concept that is supported by an OOP language, such as Java or C++. Each language varies slightly in it’s approach, but the basic idea is that the language provides you with a way to define an object that you want to use, and then you can generate as many, or few, of those objects as you need.

In C++, you create (or instantiate) objects by declaring a class. A class acts as a template for your object creation. A class contains methods that dictate how the object can be used and how it will respond to stimuli.

The main principles of OOP

This is a subject open to debate, but I think there are 3 core principles of OOP, which memorably spell out the word PIE:

1. Polymorphism

The hardest one to define. Polymorphism describes the ability of different objects to be accessed by a common interface. If that makes no sense, don’t worry, I’ll be covering this next week, and later providing a simple example, so when someone asks you in an interview, “Can you explain polymorphism to me?” you will never be at a loss for words again.

2. Inheritance

Inheritance describes the ability of objects to derive behaviour patterns from other objects. This is an amazing concept which opens up the ground for easily creating interfaces/APIs, and reducing the duplication of code in your program. I’ll take a closer look at this shortly.

3. Encapsulation

Encapsulation describes the ability of objects to maintain their internal workings independently from the program they are used in. This basically means that you define object-related behaviour inside your object, and it therefore becomes self-reliant – you don’t need to have supporting code in place for your object to work correctly. Again, I will cover this in more detail very soon.

So there you have it. The three cornerstones of OOP, and a nice handy definition of each. Next stop: a more detailed look at polymorphism, coming next week!

*Random book recommendation
Whenever I hear the abbreviation OOP, I always think of Douglas Coupland’s novel, Microserfs. It’s getting on a bit now, but is still a fab book about disillusioned Microsoft employees leaving to create a startup. Give it a go: non-affiliated, just-for-the-love-of-it link to it on Amazon here.

Creating Your First C++ Program in Eclipse

Have you seen my C++ Eclipse Masterclass
It’s a series of professional video and text tutorials on using C++ and Eclipse CDT.

This is a tutorial on creating and understanding a ‘Hello World’ program in C++ using Eclipse.

Why? Because in the majority of my other C++ tutorials I will be using Eclipse as the IDE (integrated development environment), and building on a basic project such as this.

I program on Fedora Linux, not Windows, so although your screenshots may differ slightly to mine, Eclipse runs quite happily on both.

Setup

There’s a wealth of information on the Eclipse website that tells you how to install Eclipse for your operating system, but the heads up if you’re a Fedora user is just switch to root (or use sudo) and run:

yum install eclipse-cdt

Create your project

Open eclipse (you’ll find it in the Applications > Programming menu), and if this is the first time you have used it, accept the default workspace and close the welcome window.

Then go to:

Window > Open Perspective > Other > C/C++

This opens the C++ ‘perspective’ in Eclipse, which is a fancy way of saying it makes available the windows and options you need to develop C++ programs.

Now create your first program with:

File > New > C++ Project

Name it Hello, and select the project type as Hello World C++ Project (Figure 1).

create project window
Figure 1: Create a Hello World C++ Project

Click next and accept all the defaults in the Basic Settings window. Click next and again accept all the defaults in the Select Configurations window. Click Finish.

Eclipse will create your project and project file and return you to the main C++ view. You should now be able to see your ‘Hello’ project on the left hand side of the screen, and the contents of the Hello.cpp file in the main window. If you expand the project folder on the left, and then expand the ‘src’ folder underneath it, you will see the location of your program file, Hello.cpp (Figure 2).

hello world project
Figure 2: Your Hello World Project

Your project in action

Now all you have to do is hit ‘Run’ (it’s that little green button that looks like a play symbol).

Note: Eclipse may be set to NOT build automatically, in which case you will get an error about the binary not being found. If this happens, select Build (the hammer icon) before trying to Run.

You should see “!!!Hello World!!!” in the console area at the bottom of the screen (Figure 3). Note that if you prefer a pop-up console window, you can right click and select the ‘Detached’ option on the console tab. Even if you close the window, it will reappear next time you run the program.

console output
Figure 3: Console output

That’s great, but what does it all mean?

Let’s just run through the contents of the Hello.cpp file, so you have an idea of what you have created.

The first 7 lines are just comments. They were created for you by Eclipse and you can edit these to your heart’s content. What’s included at the top of a cpp file varies widely between companies and also depends on personal preference, but bear in mind that the point of the comments is to tell the next person that comes along a little bit about what this file contains.

The first two lines of actual code are:

#include <iostream>
using namespace std;

Any line that starts with a # character is called a ‘preprocessor directive’. The preprocessor makes any requested modifications to your source code before passing it to the compiler. In this example, line 9 is telling the preprocessor to include something called ‘iostream’, which refers to a header file that allows our program to utilize the input/output methods in the iostream library.

I will talk a little more about the preprocessor in a future tuturial, but for now you can look at this line as a succinct way to include pre-existing code.

Line 10 makes use of the using directive to tell the compiler that we are using functions from the standard namespace.

Eh?

OK, a namespace is basically a collection of classes and functions grouped together under an umbrella and given a name. In this case the name is std, and it covers all the things you might want to use from the C++ standard library. Namespaces help resolve the potential issue of classes and functions having the same name and thus causing redefinition errors when you try to compile your program.

In our example, the functions we are using from the standard library are cout and endl. If you didn’t have line 10 in your source file, you wouldn’t be able to use these, because they would not be in scope, or in other words, the compiler would not know what on earth you were referring to*.

Next we have:

int main() {
    cout << "!!!Hello World!!!" << endl;
    return 0;
}

This is the most important part of the file – it’s referred to as the main function and is where our program starts and ends. main is defined only once for any C++ (or C) program, and the name is always all lower-case.

It contains two statements inside a set of curly brackets. The first uses the function cout to print the ‘Hello World’ text to the screen (or standard output), and finishes with endl, to declare an end of line character (the equivalent of pressing the return key after typing in a sentence).

The second statement returns a zero when the program exits. Traditionally a zero return means that the program has executed without errors. It is required here because the main function return type is declared as int (short for integer), meaning a whole number of some value must be returned when the program exits.

Tell me what I’ve learnt

Well, that just about covers it. Of course, you can dig into the details of just these few lines of code and read a huge amount on the hows and whys of it all, but to summarize what this basic tutorial covers, you should have done the following:

1) Created a Hello World C++ program in Eclipse.
2) Run that program and seen the output in the console window.
3) Identified the different parts of the program: comments, preprocessor directive and code.
4) Understood the importance of the main function being our program’s entry and exit point.
5) Noted the use of the std namespace to allow us access to the functions cout and endl.
6) Appreciated the use of these functions to output a text message to the screen.

Phew! That’s enough for today. Look out for the next C++ tutorial, coming soon.

*An alternative to the using directive at line 10 is to qualify each std method with its namespace when it appears in the code, i.e.:

std::cout << "!!!Hello World!!!" << std::endl;

This is considered a better way of doing things, but typing std:: over and over can be a little laborious, hence the widespread use of the using directive on line 10. If you are after more detail, there is a good explanation of this at the C++ FAQ here.

10 signs the C++ will make your life hell

You think it’s going to be great. There are subtle signs it isn’t…

There’s an exciting new task on the horizon. You’re really looking forward to getting your teeth into something new. The morning finally arrives when you get to sit down and take a look at your new charge. Oceans of lovely C++ code, untouched by anyone for months, maybe years, and now it’s all yours. You dream of the efficiency improvements you will make, of the features you’ll be able to add that will make you look like the department coding superstar.

Yes – this project is going to be the making of you.

Two days later, you’re pounding the desk in frustration as yet another attempt to improve a class or function doesn’t work quite as you expected. What small changes you have managed to make leave you with a feeling of uncertainty since the program is crashing intermittently and you have a suspicion that your code might be the reason.

There’s no documentation, you can’t understand the endless layers of complexity, and the whole thing seems to have been written by someone who wanted to deliberately obfuscate everything they were doing.

Your manager is asking questions about timescales and suddenly you realise your predicament for what it is:

LEGACY CODE HELL!

Here are 10 signs to help you see it before it hits you:

1. There are more than fifteen class header includes at the top of each .h file, and an additional five that are commented out.

2. Some classes contain methods that are thousands of lines long.

3. All the variables have tiny names, like “i”, “n” and “_kl”.

4. The ghosts of programmers past have written unanswered questions instead of comments in the code:  “//Is this a call for registering??”

5. A base class has overloaded the ++ operator, so it does more than just ++.
(It takes you three days to work this out, as the effect is so subtle you start to think you are actually going mad before you stumble upon the root of the problem)

6. Coupling and dependence is so high, every time you change anything the program segfaults when you run it.

7. Code is obviously copied and pasted between lots of different cpp files that all do a similar, but not-quite-the-same, thing.

8. Everything is mutexed to within an inch of its life.

9. The code is compiled without -Wall.

10. You turn on -Wall and get 532,764 warnings.