Writings on what I've learned as I study my two favorite programming languages C++ and Python.

Wednesday, May 28, 2008

C++ Conversion Functions

I have been using C++ for years now but I still couldn't claim mastery of all the syntax yet. Well, I haven't read a C++ book from cover to cover, that's my (shameful) excuse! In a way, however, it makes life with C++ more interesting every time you get to learn new things with it. Today, I bumped into conversion functions, which are typically used for cast conversion.

Let me show you this simple example to illustrate what conversion functions are:

class MyString
{
public:
MyString(const char * ch = "") : _value(ch) {}
virtual ~MyString();

operator const char * () { return _value; }

private:
const char * _value;
};

Here, the operator function is a conversion function that allows the MyString class to be cast as a const char *, as shown below:

#include <iostream>
#include <string>
#include "MyString.h"

int main ()
{
MyString ms("Hello World!");

std::cout << "MyString ms is " << ms << std::endl; //!==> USE CASE 1

ms = "hehehe";

std::cout << "MyString ms is " << ms << std::endl;

if (ms == "hehehe") //!==> USE CASE 2
std::cout << "ms matches const char * !!!" << std::endl;
else
std::cout << "nope." << std::endl;

std::string str = "hehehe";

if (str == static_cast<const char *>(ms)) //!==> USE CASE 3
std::cout << "ms matches std::string !!!" << std::endl;
else
std::cout << "nope." << std::endl;

return 0;
}

The output is as follows:

MyString ms is Hello World!
MyString ms is hehehe
ms matches const char * !!!
ms matches std::string !!!

As we can see, the conversion function allowed MyString to be treated as const char *. In use case 1, the streaming operator converts ms. In use case 2, we have the equality operator calling the conversion. In use case 3, however, std::string's equality operator does not call the conversion function. Hence, we need to cast it explicitly. Without the conversion function in MyString, the three use cases would have generated compilation errors.

That's all for now. Ta-ta!
-- Allister (http://cxxpython.blogspot.com)

No comments: