Skip to main content

Posts

Showing posts from June, 2021

Conversion to std::string and return from function

 Many times I have come across code something like the below: class AClass { public:     std::string getName(); }; std::string AClass::getName() {     return "I am returning"; } Here the member function converts the string constant to std::string while returning. This is in my opinion not necessary. This cast away some flexibility. I mean this way of converting to a std::string while returning to function does not make much sense.  Reason:  If we need in any place to get the name as const char* I need to reverse by calling string::c_str() const char* pName = instanceOfClassA.getName().c_str(); However, keeping the return type as const char* has some benefits: const char* AClass::getName() const {     return "I am returning"; } 1. const char* pName =  instanceOfClassA.getName().getName(); // No Conversion will take place 2. std::string sName = instanceOfClassA.getName().getName(); // Conversion happens to std::string  So, only based ...