Chapter 3 – Object-Oriented Programming: Part 4

Keywords: static, const

Static

Static in class

In a class, we can have static methods and variables.

A member variable means that each instance of that class will have a different copy. Static members and functions are part of the class itself, and there’s only one copy of them shared with all the instances of the class. Other than that, unlike member variables/functions, we do not need an object of the class to call / use them.

We can simply use the class name and the resolution operator (::) to access the static functions and variables.

static in functions

A static object inside of a function is created only once, when the function is first called, and will not be destroyed when we leave the function – thus, it will be persistent and keep its value in future calls.

Const

const tell us that we cannot modify the value of a variable – it is a constant.

When we have a const reference to an object, we also cannot change its value.

Using const after a class function means that we cannot modify the data members of that class.

An example of where this is usually added is in the getter functions.

We can also add const as return type, when we send our data as reference – we send our object, but as read-only, so it cannot be modified.

mutable

mutable is a keyword that, when used on a variable, it means that that specific variable can be modified even in const functions.

In our example, data1 and data2 are not marked as mutable, so they can be modified only in method2 which is also not const, but data3 is mutable and can be changed even in metthod1.

You may also like...