My name is

Raphael Cruzeiro

and I'm a

Software developer

C++ - A beginner's tutorial - Part 1

Posted by: Raphael Cruzeiro 2 years, 1 month ago

comments

So you've probably googled your way to this blog because:


  • You are new to the world of programming and want to learn about this C++ language which you heard is awesome

  • You already know another programming language and have decided that now is the time to learn C++

  • Though you already know C++ you have not used it for a while and now you want to refresh your knowledge on this language


Either way this article will probably be of some use to you.

C++ is a statically typed, middle-level, multi-paradigm, compiled programming language. It was developed by Bjarne Stroustrup between 1979 and 1983 at Bell Labs as an enhancement to the C programming language.

The C++ programming language can be analyzed in four cores:


  1. C. C++ began as an enhancement to C so it's most important core, the one that connects all of the other three is C itself. The basic structures of C++ all came from C; blocks, statements, preprocessor, built-in data types, arrays, pointers, etc.

  2. Object-Oriented C++. This was the first enhancement that C++ brought: the concept of classes, encapsulation, inheritance, polymorphism, virtual functions, etc

  3. Template C++. This is the core that enables you to do generic programming, that is, write generic classes and functions that manipulate a data type to be defined later by the caller.

  4. STL. Thanks to the generic capabilities granted by the template core, C++ has a Standard Template Library which is basically a collection of generic containers, iterators, algorithms, and functors.


Before continuing, I strongly suggest that you take a quick tutorial of C as C is the basic building block of C++.  Don't worry too much about the standard library's functions, just pay attention to the basic syntax (the syntax is actually simple as C was designed to be a language that you could learn all of it's syntax in one/two days. This simplicity in C's syntax is what makes C a hard language, you have only the basic building blocks.). From now on I'll assume that you have a basic understanding of C.

Why C++?


C++ , being mostly an enhancement to the C programming language,  has access to all the low level features of C but being an Object-Oriented language with templates it can also enable us to encapsulate all those low level features and reuse code so that the overall complexity of our code is greatly diminished.  So putting it in a simple way: C++ has the best of both worlds.

This is the standard C Hello World, it conforms to the C programming language specification and it will also compile on a C++ compiler (95% of ANSI C code will compile on most C++ compilers.)

#include<stdio.h>


int main(void)
{
    printf("hello, world\n");
    return 0;
}

And this is the standard C++ Hello World:
#include<iostream>


int main()
{
   std::cout << "Hello, world!" << endl;
}

As you can see there are a few differences from the plain-C version: First of all, C++ defines a new IO library, the iostream,  this library provides a simpler way to handle input and output by mean of operator overloading (a nice feature that is not available on plain-C that when used correctly provides a simpler syntax to do operation on our objects by creating a custom logic to the language provided operators).  And the second difference is that on C++ it's not mandatory to return anything from the main method (main's return type should still be int but you can choose not to return '0' as the compiler will automatically add the 'return 0;').

The basics


Every program needs an entry point, in C/C++ this entry point is the main function. As I said before, the main function is defined as a function called 'main' that returns a value of type  int. Also, the main function can accept arguments that can be passed to it by the terminal. argc is the argument count and argv[] is the array of argument strings. Arguments can be passed via the terminal separated by whitespace.

The following program demonstrates the use of arguments on the main function:

#include <iostream>


int main(int argc, char* argv[])
{
    std::cout << "Argument count: " << argc << endl;


    for(int i = 0; i < argc; i++) {
        std::cout << "Argument " << i << ": " << argv[i] << endl;
    }
}

To compile and run this program on any Unix-like system with gcc and  g++ installed navigate to the source code's directory and type:
g++ Tutorial_01.cpp -o Tutorial_01
./Tutorial_01 Argument1 Argument2 Argument3

(to install gcc and g++ on Linux type sudo apt-get install gcc g++, to install them on the Mac just download the latest version of Xcode)

This simple program will generate the following output:

Argument count: 4
Argument 0: ./Tutorial_01
Argument 1: Argument1
Argument 2: Argument2
Argument 3: Argument3

As you may have realized, cout is an object that represents the standard output stream. The std in front of cout is the namespace where this object is contained. A namespace is basically a logical container of names, it was designed to prevent name clashes withing our programs. We can avoid having to prefix every objects of a namespace with the namespace's name by using the  using statement:
#include <iostream>


using namespace std;


int main(int argc, char* argv[])
{
    cout << "Argument count: " << argc << endl;


    for(int i = 0; i < argc; i++) {
        cout << "Argument " << i << ": " << argv[i] << endl;
    }
}

If you wish to write to the standard error stream you can use the cerr object in the same way that you used  cout in the previous examples.

The standard input stream can also be accessed the same way:

#include <iostream>


using namespace std;


int main()
{
    int a = 0;
    cin >> a;
    cout << a << endl;
}

If there is an error converting the input (e.g. an user enters a non-numeric character for an integer, the initial value of the variable will be maintained. That's why it's important to initialize your variables or else in cases like this the variable would be just filled with random garbage).

Pointers and references


Now this is the part that always confuses aspiring C++ programmers. Up to now what we've seen hasn't been much different from languages like Java and to be honest pointers and references are only different for the fact that C++ doesn't hide them beneath a layer of abstractions.

Pointers are an important aspect of C that has been inherited by C++. A pointer basically is a primitive data type that points to a memory address. Take a look at the following example:

#include <iostream>


using namespace std;


int main()
{
    int a = 5;


    int b = a;    


    // Creates a pointer to an integer and point it to the value of a
    int *c = &a; 


    // Prints something like 0x7fff5fbff9dc
    cout << c << endl; 


    // Prints 5
    cout << *c << endl;


    // The variable pointed by c has the value of 7
    *c = 7;


    // Prints 7
    cout << a << endl; 


    // Prints 5 as b is a copy of a when a's value was still 5
    cout << b << endl;
}

The & operator basically mean 'address of' and the * operator means 'value pointed by'.

You can also have pointers to members:

#include <iostream>


using namespace std;


struct Vector3
{
    int x, y, z;
}vec;


int main()
{
    vec.x = 1;
    vec.y = 5;
    vec.z = 67;


    Vector3 *vecPtr = &vec;


    cout << vec.z << endl; // Prints 67
    cout << vecPtr->z << endl; // Also prints 67
}

When interacting with an API written in plain-C it's extremely common to find functions declared as something like this:
void doSomething(int *n1, int *n2);

Passing pointers to functions is particularly useful when you want a function to have more than one return value or when you need to pass a complex data type (i.e. a struct or an object) and the overhead to copy this argument is to great to be ignored. This is so common that C++ defines a new way to reference a variable; this new way is called, well, a reference. The previous example could be rewritten using references instead of pointers:
void doSomething(int &n1, int &n2);

The nice thing about references is that they are immutable, that is, once initialized you cannot change the reference and you can use the reference the same way you could use a value type. Just don't try to change their references and you can forget that n1 and n2 are references at all. When manipulating a struct or an object via references you can also access it's members via ' . ' and forget about the ' -> '.

I strongly suggest that you play around with pointers and references a bit to see that basic concepts by yourself. When you'll be able to read this common implementation of strcpy of the C standard library and understand what's happening then you'll know you have mastered pointers:

char *strcpy(char *dest, const char *src)
{
   char *save = dest;
   while(*dest++ = *src++);
   return save;
}

So far we have concentrated basically on the C core of C++ and listed a few of C++'s improvements. The part 2 of this tutorial will concentrate on the Object-Oriented core of C++.