Programming‎ > ‎Language‎ > ‎C++‎ > ‎

Keywords

The Bird's the Word

This is my notes on some of the reserved keywords in C++. Look at cppreference.com for a full list. Many keywords are used for more then one thing.



Loop constructs
for

Range-based for loops
Makes it easy to loop over a collection.

for(int i : ai)     //
for(auto &x : ax)   // Use a ref allows modifying and avoids copy.

do

while



break

continue

Conditional statements
if


else
switch, case, default(1)

Fundamental types
void
Used to create pointers to void (any type) and to indicate lack of return value and lack of arguments to functions.

nullptr (C++11)
Null pointer type designed to replace C's NULL or 0. It removes the ambiguity if it is a pointer or a number when passing it to function calls.

bool - false / true
Type that holds one of the two values: true or false. They are also keywords. The value of a sizeof(bool) is implementation defined and might be different from 1.

char / wchar_t and (since C++11) char16_t / char32_t

int
Create a integer type.
  • signed / unsigned : These keywords select if it can be positive/negative or positive values only.
  • short / long / long long: Size of the int and how big values it can contain. Implementation defined.

float / double
Creates a floating point type, usually of the IEEE-754 form.

auto (C++11)
Specify that the variable that is being declared should be automatically deduced from it's initializer. It can be used to create a iterator to loop the content of an STL container for example.
Generalized function return type deduction (c++14)
Use auto as the return type of the function to let the compiler deduce the return type based on the return call in the function.

String (c++11)
UTF-8   u8"Hello world"
UTF-16  u"Hello world"
UTF-32  U"Hello world"
Raw     R"Hello \ world"




User-defined types



enum
Declares an enumaration, a distict type that consist of a set of named constants. This is a unscoped enumeration with the named constants in the same scope as the enum name. In C++11 it is also possible to specify the the underlying type of the enum.
enum class (C++11)
This is a scoped enum that improves some of the issues that was common with the enum.
  • They don't convert implicitly to int.
  • They don't pollute the surrounding namespace.
  • They can be forward-declared.
  • You can specify the underlying type for the enum.


class

typedef
This keyword is used to create an alias name for another datatype. Often used to simplify the syntax for complex types.

typedef int AnimId;
typedef int (*AnimCallback)(int)

using
Like typedef this keyword is used to create a named alias for another datatype. Using also support templates.

using AnimId = int;
using AnimCallback = int (*)(int)



Data initialization

int i;                  // uninitialized built-in type      
int j=42;               // initialized built-in type
int k(666);             // initialized built-in type
X x1;                   // default constructor
X x2(1000);             // Parametrized constructor
X x3=x2;                // copy-constructor

Initializer List (c++11)
Support to use brace Initialization syntax on any user-defined type. Do it by adding support of constructor/assignment operator from std::initializer_list. 

Default member initializer:
In-class member initializers is when you assign the default value inside the class. It provide the compiler with the default value at the same time as it learns it exist. This should be the standard way to init member variables.
Member initializer list:
This set the values before a constructor run. The member variables is still initialized in the order they are declared in the class so write them in the same order here.

Member Assignment




access specifiers
private
protected
public

friend


Member function specifier

inline
Let the compiler know that we would like the function to be inlined in each place where it is called instead of leaving the function call in the compiled code. It is a hint to the compiler and it might ignore it. It might also do it with other functions that we have not marked as inline.
Inline namespaces (C++11)
Namespaces can be nested inside each other. A nested namespace marked as inline will be put inside the parent namespace.

explicit
C++ can use implicit conversion to resolve the parameters to a function. This is done using constructors callable with a single parameter to convert from one type to another. The explicit keyword lets you tell the compiler that it is not allowed to use it for implicit conversion.
virtual
Specify that a non-static member function is virtual. It will support dynamic binding and can be overridden in derived classes.
override (C++11)
Add override after any virtual function in a derived class. It ensures that the function is really overriding a virtual function from a base class.

Final (C++11)
Can be used on virtual function declarations or classes to specify that it can not be overridden or derived from.
= delete (C++11)
If a deleted function is used the program will not compile. That includes both explicit and implicit function calls. Useful to do to special member functions to limit copy of an object.

= default (C++11)
Tell the compiler to generate member function.

Special member functions
Member functions that are called by the code automatically when needed. Some of them are defined by the compiler even if not defined by the user.

Constructors
Called to initialize a object when it is created.
  • Delegating Constructors (C++11)
    • Constructors may call other constructors.
Copy constructor

Move constructor (C++11)

Copy assignment operator

Move assignment operator (C++11)

Destructors
Called when the the lifetime of an object ends.



cast
dynamic_cast<>
reinterpret_cast<>

static_cast<>
Converts Y to X and return it. No checks are made that the cast is valid. If A is not related to B in any way using the pointer returned is undefined.

const_cast<>
To modify the constness of a object pointed to by a pointer const_cast is used. It can be used to set or remove const from the object. Useful when using api's that can not be modified so one needs to send in a non const pointer.

Run-time type information
RTTI is a way to allow the type of on object to be determined when the program is running.

typeid

Exceptions
try

catch

throw

noexcept (since C++11)
Tell the compiler that the function should not throw any exceptions. If an exception is thrown by the function the program will terminate at runtime.

type qualifiers
const
Const is used to inform the compilers that something should not be allowed to change. It can be a variable, arguments to a function or a member function. The main use of const is to prevent programming mistakes. Const is like the Borg so when you start adding it to you code you will need to add it everywhere where it's needed.

http://www.cprogramming.com/tutorial/const_correctness.html

volatile
Tells the compiler that every access (read or write operation, member call, etc) to the object must be performed and can not be optimized away even if it looks like the action is redundant. It can be used when accessing memory ports to hardware that do not act like normal memory.

mutable
Used on non-static and non-const data members of a class this tells the compiler that it is legal to assign a value to this data member from a const member function. This can be used on internal data that does not change the externally visible state of the class. One example is a class where advanced calculations are needed to get some form of data about the object. It can then be stored in a mutable variable so it can be updated any time even in a const accessor function.


Memory
delete
new


alignas (C++11)
Specifies the alignment requirement of a type or an object.

alignof (C++11)
Get the alignment requirements of a type, in bytes.

sizeof
Return the size in bytes of the object or type.

Storage
register (deprecated C++11)
Hint's the compiler to place the object in a processor register. Deprecated in C++11 as the compiler does as it wish anyway.

static

extern (c++11)

Declare a template specialization extern to tell the compiler not to instantiate the template functions in the module. Then explicitly instantiate the class template in one cpp module. Improves compile speed, obj file size and link time.

template class vector<Entity>;          // In a single module
extern template class vector<Entity>;   // In all other modules (from h file)



thread_local (C++11)


Namespace
namespace


using
Like typedef this keyword is used to create a named alias for another datatype. Using also support templates.

using AnimId = int;
using AnimCallback = int (*)(int)
template<typename T> using setEntity = std::set<T std::greater<T>>;


Others
asm

constexpr (C++11)
Declares a function or variable that can be evaluated at compile time. Limited to a single return expression in C++11 but in C++14 more things can be used as long as it does not have any side effects outside the function.

decltype (C++11)
Trailing return type
Use auto as a return type in a function then use -> decltype() after the function to tell the compiler to find out the return type. For templates.

export

goto

typename

this

Lambda expressions

static_assert (C++11)
Performs an assertion check at compile-time. If true nothing happens, if false the compiler displays the specified error messages. Useful with template code to verify that the template will work with the provided types. The content of the <type_traits> header is useful when doing that.

template
template

Bitwise operation



Attribute (C++11)

Attributes is the standard syntax for implementation-defined attributes for types, objects, etc. Only standard attributes listed below.

[[noreturn]]
Indicates that the function does not return.

[[carries_dependency]]

[[deprecated]] and [[deprecated("reason")] (C++14)

[[fallthrough]] (C++17)

[[nodiscard]](C++17)

[[maybe_unused]](C++17)


Other 2 ;)
User defined literals
Classes can deine literal operators to convert from special suffix literals into objects.

Generalized unions

POD
Pods, trivially copyable types, trivial types and standard-layout types

[[deprecated]] and [[deprecated("reason")] (C++14)
Compiler will issue warning if labeled entity is used. Used for: functions, classes, typedefs, enums, variablers and non static data members. 

Variadic templates
A C variadic functions is one that takes an unknown number of argument, ex printf.

Non member begin/end
Can be used on arrays. In C++ add a c for const iterators (cbegin/cend), r for reverse iterators (rbegin/rend) or combine them (crbegin/crend).

Lambdas (C++11)
A lambda expression is an anonymous, on demand function object. capturelist can be used to put get local variables that are in scope available inside the lambda code. They are normally by value so they are not the same object but using a & before the name they can be captured by reference. [=] and [&] can be used to capture all variables in the selected mode. Only non-static local variables and parameters can be captured. Data members can not be captured but this can be captured to access and modify them.  Using auto and a lambda one can store the function in a variable and call it. Uses of lambdas.

* On-the-fly callback functions.
* STL algorithms
* Custom delete for unique_ptr and shared_ptr
* Predicates for condition variables in threading API.

[capturelist](arguments) { code }


Rvalue reference
Lvalues - Things you can take the address of. They may or may not have a name.
Rvalues - Things you cant take the address of. Usually they have no name.
A rvalue reference is declared with && and binds only to temporary objects.
C++ have the copy operations (constructor/assignment) and C++11 adds the move operations, move constructor and move assignment operators.
In general, move operations should be added only when moving can be faster the copying.

std::move
std::forward

Comments