A small C++ Tip. Return values from Constructors

C++ LogoYou can’t return anything from a constructor.  One way is to use exceptions but those can bring their own issues. Google’s C++ guidelines actually stipulate no exceptions and I’ve heard it from others as well that they prefer not to use them. Some people avoid it by having a mostly empty constructor and then an init() method to do the real initialisation and return a success/fail state.

But there is a simple trick that you can use, just return the state as a reference. Here’s an example. If you want to return more values, use a struct.

#include <iostream>
using namespace std;

class Simple {
public:

    Simple(bool& failure) {
        failure = true;
    }

    ~Simple() {
    }
};

int main() {

    bool fail_flag = false;
    Simple f(fail_flag);
    if (fail_flag)
        cout << "failed " << endl;
    else
        cout << "Success" << endl;
}

Leave a Reply

Your email address will not be published. Required fields are marked *