Thursday, March 31, 2011

Implementing toString() in C++

In Java, every class inherits from java.lang.Object, which as toString() method. Hence, all classes can have the flexibility to override the toString() method. Unfortunately, for C++ things aren't so straightforward. Although we can easily override the bitwise left shift operator <<, we can do this in a more elegant manner such as below.
Printable.h
#ifndef PRINTABLE_H_
#define PRINTABLE_H_

#include <string>
#include <iostream>
using namespace std;

template <class T>
class Printable {
public:
    virtual string toString() = 0;
    friend ostream& operator<<(ostream& os, T t) {
        os << t.toString();
        os.flush();
        return os;
    }
};

#endif /* PRINTABLE_H_ */

Hello.h
#ifndef HELLO_H_
#define HELLO_H_

#include "Printable.h"

class Hello : public Printable<Hello> {
public:
    Hello();
    Hello(string message);
    virtual ~Hello();
    string toString();
private:
    string message;
};

#endif /* HELLO_H_ */

Hello.cpp
#include <string>
#include "Hello.h"
using namespace std;

Hello::Hello() : message("Hello World!") {
}

Hello::Hello(string message) : message(message) {
}

Hello::~Hello() {
}

string Hello::toString() {
    return "[Hello] message=" + this->message;
}

Main.cpp
#include <iostream>
#include "Hello.h"
using namespace std;

int main() {   
    Hello hello;
    cout << hello << endl;

    Hello anotherHello("Hi World!");
    cout << anotherHello << endl;

    return 0;
}

No comments:

Post a Comment