Cplusplus

From RedBrick Wiki
Jump to: navigation, search

Under construction.

If you have any problems with this tutorial or want to give feedback, ask questions or get additional help, please e-mail coconut<at>redbrick<dot>dcu<dot>ie or, for general Helpdesk queries, helpdesk<at>redbrick<dot>dcu<dot>ie.

C++ is an object-oriented programming language, developed as a superset of the language C, which means that the language is essentially C with more features, hence the name. However, it has since evolved into a separate language and compatibility with C is no longer guaranteed.

It is a very popular all-purpose language which is commonly utilised for game programming, and in many respects is quite similar to Java, another object-oriented language.

g++

The page Programming On Redbrick explains how to compile programs written in C++. Here we will go into more depth as to how the compiler g++ works.

A compiler works by translating your programming language (in this case, C++) into machine code, which is the basic language that a processor understands. While C++ is a universal language (source code written on one architecture will generally work on another unless special libraries are used), programs must be recompiled if they are to be used on different architectures - for example, if you are compiling on murphy, which uses the UltraSPARC architecture, you will have to recompile your program if you wish to use it on carbon or deathray, which use the Intel x86 architecture, because UltraSPARC and x86 assembly languages are completely different.

g++ is the free, open-source C++ compiler which is included with many distributions of Linux as part of the gcc package, the latter of which is a C compiler. Other popular C++ compilers include Borland C++ and Microsoft Visual C++, however these are proprietary. gcc (and g++) is the most widely ported and universally available compiler in the world.

Getting started

To begin programming in C++ on RedBrick, you first have to log in. Once you've done that, you can create a new folder for your C++ files by utilising the following command

mkdir C++

This will create a directory called "C++" in your home directory. Enter this directory by typing

cd C++

Now you're ready to create your first C++ program. For this tutorial, we are going to use the nano editor. Make a new C++ source file, that we will call "first", with

nano first.cpp

C++ source code files will generally use the .cpp extension - you may have noticed that C programs use .c

nano should be open, awaiting input. The first thing you should do is import the necessary libraries to allow input/output in your program. This is the only library we will use at this point. Make the following line 1 of your program

#include <iostream>

iostream (or, archaically, iostream.h) is a C++ header file, which is a file containing C++ code designed to be imported by multiple programs.

Now we want to create our main() function. main() is the first part of code that will be executed upon running your program. main() will typically look something like this

int main()
{
   // insert some code here
  
   return(0);
}

There are a couple of things that have to be explained here.

  • The function begins with int - an int in C++ means integer, which is simply a type of variable - in this case a number. Having the function declaration as int main() means that the function main() will return an int at the end of its execution. main() will always return an int.
  • Chain brackets { } are used to denote the code which main() contains. When you call main(), the code between these brackets will be executed.
  • // is used to make a comment. A comment is a line in your source code which will be completely ignored by the compiler. This is handy for explaining what your code does and you should quickly learn to use them frivilously.
  • return(0); is placed at the end of your main() function. The 0 is the int which is returned by the function - in this case, 0 means the program executed without any problems. Yay!!! The ; is used to mark the end of a line where a command is issued. If you omit this semicolon, the compiler will whinge at you.

So, at this point your program should look like this

#include <iostream>

int main()
{
   // insert some code here
  
   return(0);
}

The Programming On Redbrick page explains how to compile C++ programs. Just to recap, we'll go over it again (oh joy!) To indent your code as shown above, press TAB. (Proper indentation is essential programming practice.) Press CTRL+O to bring up the save option, enter to save and then CTRL+X to exit.

g++ -o first first.cpp

The -o parameter allows you to tell the compiler where you want to have the compiled program saved and what you want its name to be. In this case, it'll be compiled to the same folder as your source file, first.cpp

Your program should compile. If it does, run it by entering

./first

Nothing will happen. That's because we haven't told the program to do anything!

Wow your ma with a basic program

Open up your source file again and delete the comment line. Now it's time to get stuck into some real code.

Change your program so it now reads

#include <iostream>

int main()
{
   std::cout << "This is my first real C++ program. Epic lulz!" << std::endl;
  
   return(0);
}

If you compile this, the program should execute and print this line onto the screen

This is my first real C++ program. Epic lulz!

Hurrah! Something useful and/or interesting!

  • cout is the C++ command for issuing an output. By default, this will go to the screen. Use left-facing arrow thingies (<<) to put your output into the cout command. You can link several things together by using multiple pairs of arrows as seen in the code, without having to issue cout twice.
  • endl moves output to the next line on the screen. It also flushes the stream... whatever that means.
  • std is the namespace which contains cout and endl. We could include the entire namespace in the code, but for now we don't need to since we're only using two of its functions - therefore we'll access them directly by putting std:: in front of cout and endl.
  • The text between the " " is called a string of characters. In C++, strings are always put between inverted commas like this.

To be updated later...

Variables and operators

So, you've created your first C++ program. You must be so proud of yourself. Here's where the pain begins. We're moving on to variables and operators.

A variable is a data container which you assign a value and whose value can, by default, be changed during the execution of your program. That's why it's called a variable.

In C++, there are four variable types which you will use most

  • int as explained earlier, is a number.
  • char is a single ASCII character - a letter, a number or a symbol.
  • double is a decimal (floating point) number, for example: 5.673 or 1.0
  • string is just a string (array) of characters - you need to #include the string library for this to work as a data type.

There are other ones which you won't need as often

  • short is, depending on the compiler, a number whose bit length is shorter (or sometimes) equal to an int.
  • long has a bit length twice that of an int.
  • float is a decimal (floating point) with half the precision of a double - shit, in other words. Avoid unless you're running on a system with memory measured in kilobytes and desperately need to conserve space, like the D6. God help you.

To initialise a variable such as an int, simply use the line

int a;

This reserves memory space for an int called a. But this isn't much good, is it? We need to give it a value. If you declare the variable like above, you can later assign a value like this

a = 5;

Now a has the value of 5, however, this is the n00bs' way of doing it. Why not declare and assign at the same time?

int a = 5;

That's more like it. You'll be a RB admin in no time. Let's run through initialising other variables.

int a = 5;
double b = 10.463;
char c = 'H';
string d = "Warning: Haskell may contain traces of anti-lulz.";

Hopefully you're getting the idea. Now that we're using string, we will have to start using the namespace std in our code for the sake of speed. Because of this, you will notice the absence of std:: which may make things easier for you.

We can throw the above code into a program and make it output the variables to the screen

#include <iostream>
#include <string> // Remember to include string if you're using a string!

using namespace std; // Also remember this!

int main()
{
   int a = 5;
   double b = 10.463;
   char c = 'H';
   string d = "Warning: Haskell may contain traces of anti-lulz.";
   
   cout << a << endl << b << endl << c << endl << d << endl;
   
   return(0);
}

Note how we can print four lines, with four different variables, using one cout command by having multiple <<

Also, see how string uses inverted commas " " whereas char uses two apostrophes ' ' - this is called being unnecessary complicated. But at least this isn't Haskell, so cheer up.

So, say you want to add two numbers together for some reason which makes sense to you. How? Simple. There are several ways to do it.

int a = 2;
int b = 6;
int c = a + b;

The value of c is now the values of a and b added together. If you don't want to bother with a third variable, you can just put the answer into a or b by replacing the third line with

a = a + b;

To output c to the screen

cout << c;

Or, without having to use c at all

cout << a + b;

This adds a and b together and outputs it to the screen all in one go. Hurrah!

You can also add doubles together in the same fashion.

Say you have a few chars and you want to combine them together in order to form a word, and then print it to the screen

char a = 'o';
char b = 'm';
char c = 'g';
char d = 'w';
char e = 'a';
char f = 'f';

cout << a + b + c + d + e + f;

This will print "omgwaf" on the screen.

Another way to do it, without using variables at all, is

cout << "omgwaf";

You can also waste everyone's RAMz if you want, by using a string for no justifiable reason. Say you've already declared the chars and assigned their values

string rofl = a + b + c + d + e + f;

cout << rofl;

Remember: a string is merely an array of characters so this works with strings too. You'll learn more about arrays later.

There are other basic operators in C++.

  • + is the addition operator. It allows numbers to be added and chars and strings to be joined together.
  • - is the subtraction operator. With it you can subtract numbers.
  • * is multiplication. Multiply numbers.
  • / is division. Divide numbers.

Say you want C++ to do your maths homework for you because you feel Michael Clancy is going to fail you for being such a newb.

int a = (5 * ((12/3) - 1)) + 25

Easy as undone's mother.

This will divide 12 by 3, giving 4, then take 1 from it, giving 3, multiply that by 5, giving 15, and then add it to 25, resulting in 40, which is then assigned as the value for a. Try it yourself. Brackets are very handy for mathematical calculations in C++, just like in that yoke known as "real life".

C++ can also handle negative numbers, just as you would expect a calculator to, except this time the calculator can run 32 threads simultaneously, is about one hundred times bigger, ten thousand times louder, needs several hundred watts of power to function and only the five richest kings of Europe can afford one.

Perhaps that last part was slightly untrue.

if statements and advanced operators

A crucial element of any programming language is the ability to test whether something meets a defined condition. The most basic way of doing this in C++ is by using the if statement. Here's an example of how if and else work

#include <iostream>

using namespace std;

int main()
{
   int a = 4;
   
   if(a == 5)
   {
      cout << "a is 5." << endl;
   }
   else if(a == 4)
   {
      cout << "a is 4" << endl;
   }
   else
   {
      cout << "a does not equal 4 or 5." << endl;
   }

   return(0);
}

If is 5, the program will return "a is 5.", if it is 4, the program will return "a is 4". If it is neither 5 nor 4, the program will return "a does not equal 4 or 5."

You can use an infinite number of else if statements, linking ifs together, but it is probably bad programming practice to use too many.

Also note that if you only have one line of code following an if, if else or else statement (the line which will be executed when the condition is satisfied), you may omit the chain brackets for the statement.

if(a < 10)
   cout << "a is less than 10." << endl;

If a is less than 10, the program will return "a is less than 10."

  • == is used to see if two variables are equal. It will work for all data types except string, for which there are other functions dealt with later.
  • != not equal to
  • <= less than or equal to
  • >= greater than or equal to
  • < less than
  • > greater than

Loops

Most programming languages support loops, which are useful for executing a certain part of code over and over.

Here is a while loop

#include <iostream>

using namespace std;

int main()
{
   int a = 0;

   while(a < 100)
   {
       cout << a << endl;
       a++;
   }

   return(0);
}

This will print 100 lines of numbers, going from 0 to 99

0
1
2
3
4
5
...

The condition to make sure that a is less than 100 is checked at the start of each loop, and a is incremented by 1 at the end of each loop (denoted by a++; you can also use a-- to decrement by 1). Therefore, when a reaches 99, it will be printed to screen, then incremented. The loop will then check to see if it is less than 100, which it is not, resulting in the termination of the loop.

While loops are handy in games where you may want something to loop endlessly until the user makes an action (presses a key, for example). Here is a variation of the while loop, called the do while loop.

#include <iostream>

using namespace std;

int main()
{
   int a = 0;

   do
   {
       cout << a << endl;
       a++;
   }
   while(a < 100);

   return(0);
}

This print the same 100 lines, 0 to 99. However, the condition for the loop is not checked until the end of the loop.

If you're dealing with finite numbers of loops, you may want to consider the for loop

#include <iostream>
 
using namespace std;

int main()
{
   for(int a = 0; a < 100; a++)
   {
      cout << a << endl;
   }

   return(0);
}

This produces the same result, except in a much handier format. There are three things you declare when creating a for loop: a variable, what condition must be met for the loop to continue cycling, and what happens at the end of a loop. a is the initialised variable, the loop will continue until it reaches 100 and at the end of each loop, a is incremented by 1. Simple.

To end a loop immediately, issue the following command in your code

break;

For example, if you want the loop to end early when a certain condition is met, just use an if statement inside the loop and have the loop break if this condition is met.

Executing system commands in C++

It is possible to execute system commands from within your C++ program. If your program is command-line only, you can execute simple commands such as those to clear the screen, etc.

If you're using Linux, the code is

system("clear");

You can also do this if you're running Windows (although why would you want to?) The DOS clear command is "cls"

system("cls");

...like so!

However, it is recommended that you not use system commands in your code for something as trivial as clearing the screen. It's a resource hog and leaves a gaping security hole in your C++ program. There is a better way to do this in C++, however it requires advanced knowledge of the language and is available below under Advanced.

Functions: The Basics

It's now time to move on to functions. A function is basically the same thing as a method in Java: it is a sequence of commands which can be called upon at any time, passed parameters and set to return a value.

main() is a function - the default function for a C++ program. But what if you have some code that you don't want to put into main? Use another function.

Let's say we want to add two numbers together and print out the result. The code could look something like this:

#include <iostream>

using namespace std;

int add(int a, int b)
{
   return a + b;
}

int main()
{
   int a = 2;
   int b = 5;

   cout << add(a,b) << endl;

   return(0);
}

This program adds 2 and 5 together to get 7, and displays this answer on-screen.

a and b are passed as parameters to the add function - they are then immediately added together and the answer is returned. Experiment with this code to do different things.

More advanced C++

I'll get around to this someday. I'm still learning too you know!