Home > Mobile >  Why I am not getting the second string s2 on the display?
Why I am not getting the second string s2 on the display?

Time:08-28

//In this program I convert a String (user defined type) to a C-string and then I display it. I have derived a class Pstring from the String class that also check whether the string passed by the user does not exceed the size of the String object. If it then only size-1 characters will be copied in the C-string else the whole string will be copied. In this program below s2 string is not displayed, Why???? Help.....

 #include<iostream>
 #include<cstring>
 using namespace std;

class String                                               // user defined string type
{
    protected:
       enum { SZ = 80 };                                // size of all String objects
       char str[SZ];                                    // holds a C-string
   public:
      String()                                         // no-argument constructor
      { str[0] = '\0'; }

      String( char s[] )                               //1-argument constructor
      { strcpy( str, s); }                             // converts C-string to String

      void display() const                             //display the String
      { cout << str ; }

      operator char*()                                 // conversion operator
      { return str; }                                  // converts String to C-string

  }; 

class Pstring : public String       // class Pstring ( derived publically from String class)
  {
     public:
      Pstring() : String()                        // no-argument constructor
      {     }
      
      Pstring( char s[] );                        // 1-argument constructor declared
 };

 Pstring::Pstring( char s[] )                        //1-argument constructor
   {

        if( strlen(s) > SZ-1 )
         {
            for( int i = 0; i < SZ-1; i  )
                str[i] = s[i];
                
            str[SZ-1] = '\0';
               
         }
         else 
             String(s);
   }

   int main()
  {
      Pstring s1, s2;
       s1 = "My name is Lakhan and your name is Ram Kumar. My age is 35 and your age is 40 
            then how I am your uncle"
           " You are a damn duff who can't understand this small thing that whether a thing is 
           right or wrong";
       s2 = "My name is lakhan and your is what??";

   cout << "\ns1 = "; s1.display();
   cout << "\ns2 = "; s2.display();              // Here is the problem( it is not displayed)

   cout << endl;
   return 0;


 }

CodePudding user response:

You call the constructor of the parent class String(s); but that in itself does not save the content s in str.

Change it so something like this:

Pstring::Pstring(char s[]) { // 1-argument constructor
  if (strlen(s) > SZ - 1) {
    ...
  } else { 
    strcpy(str, s); 
  }
}
  • Related