I'm trying to do something that someone told me might not be a good idea. I'm hoping I could get a few opinions please... :)
I'm trying to build a bunch of functions for manipulating strings. Trying to put them in a class that can behave a lot like the standard library string and that can accept strings typecasted.
#include <iostream>
usingnamespace std;
class BetterString : public string {
public:
BetterString(const string &s) : string(s) {};
~BetterString(){};
string someResult(int x){
returnthis->substr(x); //this is just filler code for now
}
string& doSomething(int x){
*this = this->substr(x); //this is just filler code for now
return *this;
}
};
int main(int argc, constchar * argv[])
{
string s1 = "my string";
string t1 = s1.substr(3);
string v1 = s1;
v1.replace (3, 2, "cool ");
cout << s1 << endl << t1 << endl << v1 << endl;
BetterString s2 = (BetterString) "my string";
BetterString t2 = s2.someResult(3);
BetterString v2 = s2;
v2.doSomething (3);
cout << s2 << endl << t2 << endl << v2 << endl;
return 0;
}
Of course it's relatively useless, but for now it's just a concept. It compiles and runs ok (XCode 5.1 Mac OS X 10.9.2) but is this code asking for any trouble, or is it perfectly reasonable?
//You have public string inheritance, that means you are able to use
//your class everywhere where you can use string
std::string* edit = new BetterString;
/*...*/
//Deleting
delete edit; //Whoops. Memory leak and incomplete destruction!
Rules of thumb:
1) do not inherit publicily from classes with non-virtual destructor.
2) all single argument constructors and conversion operators should be explicit unless you have a very good reason against it.
I suggest you to build a wrapper over string instead.
So in short, is there just no safe way to do this? Is there no way to change it to make it safe?
Is the incomplete destruction the only reason why this is bad? And if so, is there's no (sensible) way around it?
Thanks!
PS. Sorry if these questions seem stupid. I'm a relative newbie. I've just discovered the Beginners section of this forum and maybe I should have posted this there? Still if you can help me understand this I'd be very grateful.
You cannot use it to overload std::string methods and pass it as reference to std::string (read: use it with standard library) because std::string have no virtual functions at all.