C++ Features

  • Compiled and fast: the code is changed to machine code, so there is almost no overhead.
  • Object oriented: classes, objects, inheritance, polymorphism, encapsulation.
  • Multi paradigm: you can write procedural, object oriented and generic code (and some functional style) in one program.
  • Templates and generic programming: write one function or class for many types.
  • Standard Template Library (STL): ready containers (vector, map), algorithms (sort, find) and iterators.
  • Memory control: pointers, new and delete when you need them, and RAII with smart pointers to be safe.
  • Zero cost abstractions: high level features (like classes and templates) should not make the program slower than hand written code.
  • Portable: the same standard code runs on Windows, Linux, macOS and embedded devices.
  • Close to C: most C code works in C++, and you can use C libraries.

RAII: a feature to understand early

RAII (resource acquisition is initialization) means that an object takes a resource in its constructor and frees it in its destructor. When the object goes out of scope, C++ calls the destructor by itself. This gives safe memory handling, without a garbage collector.

#include <iostream>

struct Guard {
    Guard()  { std::cout << "resource opened\n"; }
    ~Guard() { std::cout << "resource closed\n"; }
};

int main() {
    {
        Guard g;
        std::cout << "using the resource\n";
    }   // the destructor runs here, automatically
    std::cout << "after the block\n";
}
Output

resource opened
using the resource
resource closed
after the block

See the chapters on constructors and destructors and smart pointers.

Note: C++ gives you power and also responsibility. Modern C++ has tools which make the safe way the easy way. Next: C++ vs C.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.