Home > Software design >  Extending built-in classes in C
Extending built-in classes in C

Time:09-17

I know extending built-in classes in C is deprecated, but still I want to do it for some reasons.

I wanna add my custom methods to a class (str) that extends/inherits from the std::string class (this is for an example)

But when I do so there's some problem I am facing with the methods that are already there in the std::string class (built-in methods), for example,

#include <bits/stdc  .h>
using namespace std;
class str : public string {
  public:
    string s;
    str(string s1) {
      s = s1; //ig the problem is here
    }
};
int main() {
  str s("hello world");
  cout << s.size(); //prints out 0 not 11 => length of "hello world"
}

How do I get around this?

CodePudding user response:

std::string doesn't know about your string s; member. It cannot possibly use it in its methods. If you want to use inheritance over composition, you need to use whatever is available under public interface of std::string - in this case, its constructors.

class str : public string {
  public:
    str(string s1): string(s1) //initialize base class using its constructor
    {
    }
};

// or

class str : public string {
  public:
    using string::string; //bring all std::string constructors into your class
};

As a footnote, there is nothing deprecated about inheriting from standard containers, but they are not meant for that and you can only do a very limited set of things safely. For example, this is Undefined Behaviour:

std::string* s = new str("asdf");
delete s; // UB!

More detailed explanation in this question.

Also, you should strongly avoid <bits/stdc .h> and using namespace std; and in particular you should not mix them. You will strip yourself of almost every name and it produces hard to find bugs.

  • Related