Beranda > CPP > Explicit Keyword in C++

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

Iklan
Kategori:CPP Tag:
  1. Belum ada komentar.
  1. No trackbacks yet.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: