Skip to content

Lab 0: Introduction to Cpp

drebain edited this page May 9, 2017 · 1 revision

Lab 0: Introduction to C++

In this lab you will learn how to implement a basic C++ program. This tutorial is designed for people with a background in Java. If this is not the case, it should still be fairly straightforward to understand this lab, but please ask the TA for help if necessary.

Technologies covered in this lab will include:

  • CMake www.cmake.org.
  • The basic program structure of a C++ program.
  • Function call and parameter passing by value, pointer or references.
  • The basic structure of a C++ class.

Helloworld in C++

First, we will create a CMake to automatically generate a Makefile for Unix (Mac, Linux) or a Visual Studio solution for Windows. CMake is a cross-platform tool to for compiling your source code on different operating systems.

For Qt Creator, Go to File > New File or Project > Non-Qt Project > Plain C++ Project (CMake Build), and press "Choose..." to set up your new CMake project. Edit the CMakeLists.txt file to make it looks like the following:

# Declaring the used CMAKE version is mandatory
cmake_minimum_required(VERSION 2.8)
# This defines the name of our project (i.e. name in IDE)
project(helloworld)
# This creates an executable called "main" from "main.cpp"
add_executable(main main.cpp)

Then take a look at the automatically generated main.cpp file. Here is a version with comments to explain what is going on:

///========================== main.cpp ==========================
/// iostream provides basic input/output functionalities (cout)
#include <iostream>
/// iostream is part of the "std" namespace. The keyword "using" can 
/// be employed to avoid typing std::cout throughout the code
using namespace std;

/// main is the entry point of your program. It needs to be 
/// defined and always have this signature. The argc and argv 
/// are used to pass parameters from command line.
int main(int /*argc*/, char** /*argv*/){
    /// @todo find out how to print "helloworld" to terminal
    cout << "Helloworld" << endl;
    /// The main function should always return a value.
    /// This tells the application whether it exited 
    /// correctly or not (legacy error management)
    return 0; ///< also EXIT_SUCCESS on UNIX
}

The main() function is the entry point of the program and needs to always be defined (with those exact parameters).

Compile and run you C++ program and make sure that you can see the ”helloworld” text printed in the console. To compile a CMake project, first go to Build > Run CMake, then press the green triangle on the left bottom corner of the screen. If the wrong project is selected and the project cannot run, press the little computer icon above the green triangle to select the correct project.

More details on CMake can be found here.

Functions

In this section we will learn how to create simple functions in C++.

Passing Parameters by Value

Create a function that self-incremented the value passed as parameter by 1 (using the C++ ”++” operator) and that returns it. Call this function from the main function and print the original and incremented value in the terminal.

///========================== main.cpp ==========================
#include <iostream>
using namespace std;

int myfunction(int value){
    value = value+1;
    return value;
}

int main(int, char**){
    /// @todo
    /// 1) declare (and initialize!!) a variable "int a"
    /// 2) implement and call "myfunction(...)"
    /// 3) print the original and incremented value
    /// QUESTION) what happens if you don't initialize a?
    /// QUESTION) what happens if you declare "int a" twice?

    return EXIT_SUCCESS;
}

Passing Parameters by Reference

You may recall that in Java objects are automatically passed by reference and in Java/C native types (i.e., int, float, double, ...) are passed by value. This is not the case in C++ where references need to be declared manually!

///========================== main.cpp ==========================
#include <iostream>
using namespace std;

void myfunction_reference(int& val){
    val++;
}

int main(int, char**){
    /// @todo    
    /// 1) declare (and initialize!!) a variable "int c"
    /// 2) implement and call "myfunction_reference(...)"
    /// 3) print the original and incremented value

    return EXIT_SUCCESS;
}

Passing Parameters by Pointer

Pointers can be considered similar to references, but they are often not as safe to use (it is easy to mess up). Complete this code by following the inlined instructions. Homework: we strongly invite you to read a tutorial on pointers such as this one.

///========================== main.cpp ==========================
#include <iostream>
using namespace std;

void myfunction_pointer(int* val){
    /// @todo increment the value by one
    /// @note val++ will not work, why?

}

int main(int, char**){
    /// @todo    
    /// 1) declare (and initialize!!) a variable "int d"
    /// 2) implement and call "myfunction_pointer(...)"
    ///    @attention you need to obtain a pointer from "d" using "&"
    /// 3) print the original and incremented value

    return EXIT_SUCCESS;
}

Classes, Objects and OOP - Part 1 : Set up the classes

Create a file Shape.h and a file Shape.cpp and add them to the add_executable() command of CMakeLists.txt. Copy the code below in these two files to define your first C++ class. Another difference from Java to C++ is that the classes are usually not defined in a single file but split in an .h (header) file where the functions are declared and a cpp (source) file where the functions are defined. Look at the following code and try to understand how to implement a C++ class. You can also find a good tutorial on C++ classes on cplusplus.com.

///=========================== Shape.h ==========================
#pragma once
#include <iostream>

class Shape{
protected:
    float* data;
public:
    Shape(int size);
    /// @todo Declare the destructor here
    virtual ~Shape();
    /// @todo Declare "member_function()" here
    void member_function();        
}; ///< @note DO NOT forget the semicolon!!!
///========================== Shape.cpp =========================
#include <iostream>
#include "Shape.h"

using namespace std;

Shape::Shape(int size){
    /// @attention memory allocated here!!!
    data = new float[size];
}

/// @todo Define the destructor here
/// 1) print "~Shape()" to terminal (which destructor is called?)
/// 2) deallocate the memory pointed to by the member "data"
Shape::~Shape(){
    std::cout << "~Shape()" << std::endl;
    delete[] data;
}

/// @todo Define "member_function()" here
void Shape::member_function(){
    std::cout << "Shape::member_function()" << std::endl;
}

/// @todo Define "virtual_member_function()" here
/// The function prints "Shape::virtual_member_function()"

This main.cpp file will make use of our class:

///========================== main.cpp ==========================
#include <iostream>
#include "Shape.h"
using namespace std;

int main(int, char**){
    /// @todo 
    /// 1) Create a class Shape (Shape.h/.cpp)
    ///    - modify the constructor to take an input parameter
    ///    - add a public member function
    ///      - declare the function in "Shape.h"
    ///      - define the function in "Shape.cpp"
    ///      - the function body prints "Shape::member_function()"
    /// 2) Instantiate an object of class Shape
    /// 3) Call the member function 

    return EXIT_SUCCESS;
}