Churkin Aleksey
Churkin Aleksey

Reputation: 39

Using class without definition class variable

I'd like to do something like:

class StrToHex {
public:
    ??? StrToHex(std::string a) {
        return class_method1(a) + class_method2(a);
    }
private:
    std::string method1(std::string a);
    std::string method2(std::string a);
}
int main() {
    std::string var = StrToHex("FF1042");
}

I know that I may use StrToHex::MyFunc() or create class object, but is there any way to do without it?

Upvotes: 0

Views: 104

Answers (1)

Nitheesh George
Nitheesh George

Reputation: 1367

In C++ a constructor cannot return a value. So you cannot specify a return type for a constructor. But there are other alternative ways to achieve the same. I have used a std::string cast operator here.

class StrToHex {
public:
StrToHex(std::string a) {
    _data = method1(a) + method2(a);
};

operator std::string()
{
    return _data;
};
private:
std::string method1(std::string a)
{
    return std::string("Hi " + a);
};

std::string method2(std::string a)
{
    return std::string(" again " + a);
};

std::string _data;
};

int main() {
std::string var = StrToHex("FF1042");
std::cout << var;
}

I hope it helps!.

Upvotes: 1

Related Questions