Monday, January 2, 2023

Modern C++ features

Modern C++

In this article, I will provide a tutorial on features in modern C++ using very simple examples. The examples will be kept short for beginners to quickly grasp the features.

The complete list of features can be found in the following links: C++11, C++14, C++17, C++20. Please refer to these links for more information.

1 C++11

1.1 nullptr

Considering function overloading:

void fun(int);
void fun(char *);

Traditionally, NULL is often defined as 0. The issue arises with which function will foo(NULL) call?

Thus, C++11 introduces a new kerword, nullptr, as a distinghished null pointer consant.

#include <iostream>

void fun(char *p) {
        std::cout << "hi pointer" << std::endl;

}

void fun(int i) {
        std::cout << "hi integer" << std::endl;

}

int main()
{
        fun(0);       // Calls func(int)
        fun(nullptr); // Calls func(char*)
        //fun(NULL);  // This generates an error
        return 0;

}

1.2 Strongly typed enumeration

Enumerations in C++03 are effectively integers and do not have their own scope. It is possible to compare two enum values of different enumeration types.

#include <iostream>

int main()
{
        enum Animal {Cat, Dog, Elephant};
        enum Fish {Clam, Dolphin, Eel};

        Animal a = Dog;
        Fish f = Dolphin;

        if (a == f)
                std::cout << "Dog == Dolphin" << std::endl;
        else
                std::cout << "Dog != Dolphin" << std::endl;
        return 0;
}