Skip to content

Instantly share code, notes, and snippets.

@MingjiHan99
Last active September 25, 2023 20:02
Show Gist options
  • Select an option

  • Save MingjiHan99/879c324fadde13c1457e78cddf587bfb to your computer and use it in GitHub Desktop.

Select an option

Save MingjiHan99/879c324fadde13c1457e78cddf587bfb to your computer and use it in GitHub Desktop.

CPP Tutorial

Introduction

In this tutorial, we are going to introduce key features of C++. We assume the readers know other object-oriented and high level languages including Java and Python.

Basics

We use a sample program to show the basics structure and syntax of C++.

// Headers files 
#include <iostream>
#include <vector>
// Namespace provides scope for identifiers.
// Reference: https://learn.microsoft.com/en-us/cpp/cpp/namespaces-cpp?view=msvc-170
using namespace std;
// Main function
int main() {
    
    std::cout << "Hello " << std::endl;
    // Or cout << "Hello " << endl; as long as namespace std is included.
    // Variables
    int a = 1;
    float b = 2.0;
    char c = 'A';
    string s = "hello";
    // Array
    int arr[100];

    // Control-flow: Loop
    for (int i = 0; i < 100; ++i) {
        arr[i] = i ;
    }
    int sum = 0;

    // Control-flow: if
    if (a + b > 2) {
        cout << "Yes" << end;
    }

    return 0;
}

Memory Management

One fundmental difference between C++ and Java is memory management. In Java, you can use new to create new objects. The JVM manages the memory allocation and Garbage Collection.

When you use C++. It requires developer to manage memory allocatiion and deallocation. C++ allows developer manage memory in a fine-grinded way using pointer, a data type refering to memory address.

Compared with Java, C++ has better performance since: 1. C++ program is compiled into binary executable program and runs above operating system directly. 2. C++ does not have garbage collection, memory managment is more efficient.

So C++ is suitable for developing efficiency crtiical softwares. C++ is wildly used in system development including databases (RocksDB, MySQL, and Doris), message queue (ZeroMQ), and deep learning libraries (PyTorch and Tensorflow).

Program Memory Layout

To understand how to manage memory in C++. We first need to understand the memory layout of C++ program.

The memory layout consists of 4 parts:

stack: stores local variables
heap: dynamic memory for programmer to allocate
data: stores global variables, separated into initialized and uninitialized
text: stores the code being executed
(Reference: https://courses.engr.illinois.edu/cs225/fa2022/resources/stack-heap/)

// Code are stored in text
int global_var; // in data

int main() {
    int a; // save in the stack
    int a[1000000]; // bad idea, the stack size is small, the program crashes
    int *p = new int[1000000];  // okay, allocate memory on the heap
    delete []p; // deallocate memory
    return 0;
}

Pointer, Memory Allocation and Deallocation

In the previous program. we use new to allocate memory on the heap to create a huge integer arrays. Then we use int * to access the return value, which is a pointer pointing the allocated memory space.

In this section, we discuss pointer and memory management in C++ in details.

A pointer is a data type storing memory address, which allows us to manage memory, read/write data in a fine-grinded way.

Reference: https://learn.microsoft.com/en-us/cpp/cpp/pointers-cpp?view=msvc-170

Here is a basic program introducing the usage of pointer.

int main() {
    // Basic usage
    int a = 1;
    int *p = &a; // Define a pointer, Use & to get the address of a.
    cout << p << endl; // print out the address of a.
    cout << *p << endl; // Dereferencing, get the value of a.
    *p = 100; // Dereferencing and assign a new value.

    cout << a << endl;
    // The output should be 100, because p points to a, and we update the value.
    int *q = new int; // Create a integer.
    *q = 5; // Set value

    cout << *q << endl; // 5
    delete p; // deallocate memory of the integer

    int *p = new int[1000000];  // Create integer array on heap
    delete []p; // deallocate memory, use [] if you use [] when you allocate memory.


    return 0;
}

Object-Oriented Programming

Now we disscuss the object oriented programming in C++. We will discuss how to defince class and how to do inheritance.

Basic Definitions

class Array {
public: 
    // Constructor
    Array(int count_): count(count_), {
        x = new int[count_];
    }

    // Destructor
    // If you allcate memory on heap when constructing the object,
    // be sure to deallcate the memory to avoid memory leak.
    // This is different from Java.
    ~Array() {
        delete[] x;
    }

    int get_element(int index) {
        return x[index];
    }
   
    void set_element(int index, int value) {
        x[index] = value;
    }

protected:
    int count;
private:
    int* x;
};

// Struct = class + all members are public by default
struct Point {
    int x, y;
}

Operator overloading

One highhlight point of C++ is that you can overload the built-in operator including +, -, *, / for your user-defined class. For more details, please visit https://en.cppreference.com/w/cpp/language/operators

struct Point {
    int x, y;
    Point(int x_, int y_) {

    }

    Point operator+(const Pointer& rhs) {
        return Point(x + rhs.x, y + rhs.y);
    }
    
    Point operator-(const Pointer& rhs) {
        return Point(x - rhs.x, y - rhs.y);
    }

};

int main() {
    Point a = Point(1, 2);
    Point b = Point(3, 4);
    Point c = a + b;
    cout << c.x << " " << c.y << endl;
    // 4, 6
}

Template

In Java, we have generics to do generic programming. In C++, we call it template.
Reference: https://learn.microsoft.com/en-us/cpp/cpp/templates-cpp?view=msvc-170

// We define generic array class using tempalte

template<class T>
class Array {
public: 
    // Constructor
    Array(int count_): count(count_), {
        x = new T[count_];
    }

    // Destructor
    // If you allcate memory on heap when constructing the object,
    // be sure to deallcate the memory to avoid memory leak.
    // This is different from Java.
    ~Array() {
        delete[] x;
    }

    T get_element(int index) {
        return x[index];
    }
   
    void set_element(int index, int value) {
        x[index] = value;
    }

protected:
    int count;
private:
    T* x;
};

int main () {
    // Passing the type for template class
    Array<int> int_arr(100);
    Array<float> float_arr(100);
    int_arr.set_element(0, 100);
    int val = int_arr.get_element(0);
    cout << val << endl; // should be 100

    return 0;
}

STL (Standard Template Library)

In C++, Standard Template Library provides developers rich data structures and algorithms to write programs. Here we give some simple examples for the usage of STL.

Reference: https://cs.brown.edu/~jak/proglang/cpp/stltut/tut.html

Containers: Pre-defined data structures.

Examples:

// vector, similar to ArrayList in Java
vector<int> vec;
vec.push_back(10);
vec.push_back(20);
cout << vec[0] << endl;
cout << vec[1] << endl;
// unordered_map = HashMap in Java
unordered_map<int, int> kvs;
kvs[1] = 2;
kvs[2] = 3;
cout << kv[1] << endl;

Iterators: Iterators to access elements in containers.

Examples:

vector<int> vec;
vec.push_back(10);
vec.push_back(40);
vec.push_back(20);


for (vector<int>::iterator iter = vec.begin();iter != vec.end(); iter++) {
    cout << *iter << endl;
}
// 10
// 40
// 20

Algorithms: commonly used algorithms including sorting and searching.
Examples:

vector<int> vec;
vec.push_back(10);
vec.push_back(40);
vec.push_back(20);
sort(vec.begin(), vec.end());
// [10, 20, 40]

Modern C++

C++ has a long history In the past ten years, C++ has many new features making it a modern programming lanuguages in C++11, 14, 17, 20, 23 stanards (in coming).

If you have some experiences in C++, you are encouraged to learn modern C++ to develop modern and efficient C++ programs.
Reference: https://github.com/changkun/modern-cpp-tutorial

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment