Drakorex
Drakorex

Reputation: 41

Class derived from string

I've got a problem and I'm not sure where to go from here.

In this program, you are going to create a class called mystring, which is derived from class string. Class mystring should include:

  • A private data member id, which is an integer, representing the ID of a string (see example in function main()).

  • A public method, constructor mystring(int, char *), which has two parameters: an integer (int) and a string (char *). It should (1) call base class constructor using the string parameter (char *) and (2) assign integer parameter (int) to id.

  • A public method int getid(), which returns id of class mystring.

Heres what I have so far

class mystring : public string
{
  private:
    int id;
  public:
    mystring(int id, char *words);
    int getid();
};

mystring::mystring(int id, char *words)
{
  string a (words);
  this->id = id;
}

int mystring::getid()
{
  return id;
}

// If your class is implemented correctly, the main program should work as
//the followings
int main()
{
  mystring x(101, "Hello Kitty");   // “hello Kitty” has an ID 101
  cout << x.getid() << endl;            //display 101
  cout << x << endl;                    //display string value: “Hello Kitty”
  cout << x.length() << endl;       //display length of the string: 11
  return 0;
}

And I get this

101

0

Upvotes: 0

Views: 955

Answers (1)

TartanLlama
TartanLlama

Reputation: 65620

In your constructor, you aren't calling the std::string base constructor for your instance, you are just creating a local string, then throwing it away.

Change this:

mystring::mystring(int id, char *words)
{
    string a (words); //creates a local string called a
    this->id = id;    //initializes id
}

To use initialization lists, like this:

mystring::mystring(int id, char *words) :
    string(words), //calls the string base constructor
    id(id)         //initializes id
{}

Upvotes: 3

Related Questions