Arsip

Archive for the ‘CPP’ Category

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 {
public:
  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: http://en.cppreference.com/w/cpp/language/type.

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.

Iklan
Kategori:CPP Tag:, ,

Explicit Keyword in C++

I am trying to do more C++ lately (after 7-8 years). Ouch, I am feeling old now. I am finding something new (or perhaps refinding). I will try post about it regulary here. So, here we go my first post:

It’s about explicit keyword. This keywords is used to prevent an implicit convertion when creating an object. See this example:

class String {
public:
    String(int n); // allocate n bytes to the String object
    String(const char *p); // initializes object with char *p
};

Then if you call

String a = '3';

It will implicitly converted ‘3’ to integer, and create String object with 3 bytes allocation. Here, we need the explicit keywords. Like this:

class String {
public:
    explicit String(int n); // allocate n bytes to the String object
    String(const char *p); // initializes object with char *p
};

By doing this, we prevent the ‘3’ to be converted to int, rather it will create String object that has char *p = ‘3’.

 

Reference: http://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-mean-in-c

Kategori:CPP Tag:
%d blogger menyukai ini: