C++ - Concepts

Updated: 2021-05-13

Declarations vs Definitions

  • Declaration: give it a name (mostly in .h files)
  • Definition: give it a name and all the info the compiler needs to create the code for that name (mostly in .cc files)

State

An object's state is the collective set of its non-static data members' values.

Copying causes a target object t to end up with the same state as the source s, without modifying s.

Storage Duration

Allocation Deallocation Notes
automatic code block begins code block ends all local objects except for static, extern or thread_local
static program begins program ends only one instance exists; objects at namespace scope, or static or extern
dynamic new delete
thread thread begins thread ends each thread has its own instance

Translation Unit

A translation unit = a source file + all (direct or indirect) header files - lines ignored by conditional preprocessing statements.

A translation unit is the input to the compiler to generate an object file.

Linkage

3 levels of linkage

  • no linkage: an entity cannot be referenced via names from anywhere else
  • internal linkage: definitions in a .cc file cannot be referenced outside the file. (Do NOT use internal linkage in .h files) Can be achieved in 2 ways:
    • for all declarations (including functions and variables): place them in unnamed namespaces
    • for functions and variables: declare them static
  • external linkage: The name can be referred to from the scopes in the other translation units.

Virtual Function

Used for Runtime polymorphism:

  • the resolving of function call is done at runtime
  • runtime polymorphism is achieved only through a pointer (or reference) of base class type.
  • not mandatory for the derived class to override

Pure Virtual Function

A pure virtual function is declared by assigning 0 in declaration.

virtual void foo() = 0;

Abstract methods in Java is same as pure virtual functions in C++. virtual functions in c++ can be overridden , but abstract method must be overridden or the class must be abstract too.This is because virtual function have a default implementation and abstract methods have none.

C++ A class is abstract if it has at least one pure virtual function.

In C++, an interface can be simulated by making all methods as pure virtual.

Compile-time(early binding) VS run-time(late binding)

Virtual Destructor

Rule of thumb: add a virtual destructor (even an empty one) if there's any virtual function in a class.