I've been using a pattern in a library I'm creating that uses passes a String name of an object to its base object's constructor. I've tried using std::string and c-style strings but keep getting weird memory errors with Valgrind.
class Base {
public:
Base( std::string name ) : name(name) {}
virtual ~Base() {}
std::string getName() { return name; }
private:
std::string name;
};
class Derived : public Base {
public:
Derived() : Base("Derived") {}
};
int main() {
Base* derived = new Derived;
std::cout << derived->getName() << "\n";
delete derived;
}
(This compiles and runs fine in Valgrind)
Is something like this safe? I'm using 'const char*' instead of 'std::string' right now, is that safe?
Is there a safer alternative, preferably without using virtuals?
Edit: Is there a way to do this with templates? I don't want to use RTTI since it has the name mangled and I want the name to be 'normal' for use with scripting/data persistance.