Posts Tagged ‘syntax’

static const in C++

When you want to use static const in your C++ code, you need to know whether the variable is integral or not. If it’s integral, you can initialize it in the header file (.h). Otherwise, you need to initialize it in the souce file (.cpp). Here some example:

// myclass.h
class MyClass {
  static const int myInt = 0; // Can be initialized here
  static const string myString;  // Need to be initialized in the source file


// myclass.cpp
const string MyClass::myString = 'My String';

If you are not familiar with integral type, you can read here:

What’s the different between static and const?

static in class member means, you do not need to hava the class instance to access it.

const to make a variable constant (not mutable).

They can be used together as const static or static const. Both are the same.

Kategori:CPP Tag:, ,
%d blogger menyukai ini: