35
loading...
This website collects cookies to deliver better user experience
.cpp
file:static bool isWineColour(const std::string& iWineCoulour) {
static const std::array<std::string, 3> wineCoulours{ "white", "red", "rose" };
return std::find(wineCoulours.begin(), wineCoulours.end(), iWineCoulour)
!= wineCoulours.end();
}
static bool
? What? I've never seen anything like that in a cpp
file and it wouldn't make sense, would it?static bool
and we are not in the header. There is no isWineColour()
function declared in the header at all.static
return type. When the keyword static
appears in front of the return type, it might be mean one of these two possibilities:static
static
with a member function in the other we use it with a free-function.#include <iostream>
#include <type_traits>
class A {
public:
static void Foo() {
std::cout << "A::foo is called\n";
}
};
int main() {
A a;
a.Foo();
A::Foo();
}
/*
A::foo is called
A::foo is called
*/
Foo()
both via an instance (a.Foo()
) or just via its enclosing class (A::Foo()
).static
member functions don't have this
pointerstatic
member function can't be virtualstatic
member functions cannot access non-static
membersconst
, const volatile
, and volatile
declarations aren't available for static
member functionsthis
pointer always holds the memory address of the current object and to call a static member you don't need an object at all, it cannot have a this
pointer.virtual
member is something that doesn't relate directly to any class, only to an instance. A "virtual
function" is (by definition) a function that is dynamically linked, i.e. it's chosen at runtime depending on the dynamic type of a given object. Hence, as there is no object, there cannot be a virtual call.static
member requires that the object has been constructed but for static calls, we don't pass any instantiation of the class. It's not even guaranteed that any instance has been constructed.const
and the const volatile
keywords modify whether and how an object can be modified or not. As there is no object...static
member functions already. Let's jump to the other usage of static
with functions.cpp
file have external linkage by default, meaning that a function defined in one file can be used in another cpp
file by forward declaration.static
and it changes the type of linkage to internal, which means that the function can only be accessed from the given translation unit, from the same file where it was declared and from nowhere else.static
free-functions entirely bringing a couple of advantages:cpp
file and we have a guarantee that it will not be used from any other placestatic
not only class member functions, but free-functions as well.