Currently building this hierarchy of objects and to be able to make the logging a bit more clear in the baseclass I decided to have some kind of variable or function that returns the type of the class.
For example:
class fruit {
string _type;
fruit() {
_type = "base"; // or i dont have to set it. however, it wont be inforced
}
virtual const char* type() const { return "base"; } // or just = 0 to inforce it
void function() {
log(this->type(), " tastes good");
log(this->_type, "tastes good");
}
}
class apple : public fruit {
apple() {
_type = "apple";
}
const char* type() const { return "apple"; }
}
As you can see there is two approaches and me personally think that the return value version is much cleaner since it is clear that it needs to be implemented.
My question however is what approach is the best one? And is it a lot slower to call a function everytime I’m logging something? Just assumed that it would be optimized but I can be wrong.
First of all, If you need to know the type of class in your program then there is something wrong in your design. Usually, You wouldn’t want to your program to depend on concrete imlpementations but to depend on interfaces.
Anyhow, the function should be a pure virtual function so that every deriving class must implement it otherwise you would end up getting the wrong types for derived classes if someone doesn’t implement it for their derivying class.
Assigning a string and returning a string literal are both fine.
String literals have static storage duration so it will be valid throughout the duration of the program, Also you appropriately have the
const charreturn type so that user doesn’t modify the returned literal and end up causing an Undefined Behavior.Returning a member is fine as well though it justs add some overhead of an additional member to your class & you are not too worried about this extra member.