Home > OS >  Not calling the appropriate constructor
Not calling the appropriate constructor

Time:04-05

#include<iostream>
using namespace std;
class String
{
    protected:
        enum {SZ= 80};
        char str[SZ];
    public:
        String (){str[0]='\0';}
        String(char s[])
        {
            strcpy(str,s);
        }
        void display() const
        {  
            cout<<str;
        }
        operator char*()
        {
            return str;
        }
};
class Pstring : public String
{
    public:
        Pstring(char s[])
        {
            if(strlen(s)>SZ-1)
            {
                for(int j=0;j<SZ-1;j  )
                {
                    str[j]=s[j];
                }
                str[SZ-1]='\0';
            }
            else
            {String(s);}
        }
};
int main()
{
  Pstring s2 ="This is a strong string.";
  cout<<"\ns2="; s2.display();
return 0;
}

s2.display() returns blank. Upon debugging it's is found that String(s) in Pstring calls the no-argument constructor in the String class. I understand it as a constructor with one argument and thus String(char s[]) should've been called. What is this behavior?

CodePudding user response:

This code snippet

        else
        {String(s);}

does not make a sense.

This line

String(s);

is a declaration of the variable s of the type String with the scope of the compound operator of the else part of the if statement.

Pay attention to that this constructor

Pstring(char s[])

calls implicitly the default constructor of the class String before the control will be passed to the body of the constructor. That is the body of the constructor gets the control only after all sub-objects of the created object of the derived class will be created.

You should place the check of the passed string in the constructor of the class String.

For example in the class String you could define the constructor with parameter the following way

    String( const char s[] )
    {
        strncpy( str, s, SZ );
        str[SZ - 1] = '\0';
    }

And the constructor in the derived class could be defined like

    Pstring( const char s[] ) : String( s )
    {
    }  
  • Related