0

Here is the example.

#include <iostream>


class my_strcmp
{

private:

char *m_src;
char *m_dest;

public:
my_strcmp(char *a, char *b);
int strcmp();

};

/** Initializer list in constructor **/
my_strcmp::my_strcmp(char *a, char *b) : m_src(a), m_dest(b)
{

  //std::cout<<"Constructor called"<<std::endl;

}

int my_strcmp::strcmp()
{
   while( (*src++ == *dest++) && ( *src != '\0') )
   {

   }

   if( (*src=='\0') && (*dest == '\0') )
   {
       //std::cout<<"Data matches"<<std::endl;
       return 0;

   }        

   else
   {

     return -1;   
   }


}


int main(int argc, char *argv[])
{
    if( argc > 2 )
    {

        my_strcmp example(argv[1],argv[2]);
        std::cout<< (example.strcmp()?"Un-Match":"Match");
        std::cout<<std::endl;
    }

    else
    {
      std::cout<<"Pass right arguments" << std::endl;   

    }

    return 0;

}

What do I gain by the following?

/** Initializer list in constructor **/
my_strcmp::my_strcmp(char *a, char *b) : m_src(a), m_dest(b)
{

  //std::cout<<"Constructor called"<<std::endl;

}

and why not by initlializing in the body? what is the gain in it?

dexterous
  • 6,422
  • 12
  • 51
  • 99

1 Answers1

0

In a simple example like this, you don't gain much. But if m_src or m_dest were larger, more complex objects (that had their own default constructor), then there might be more to gain, as the objects would first be default constructed, then assigned to (kind of wasting the whole "default constructed" work that was done).

Additionally, some types don't have default constructors, so they can't be default constructed and assigned to in the body of the constructor and have to be initialized in the initializer list.

Cornstalks
  • 37,137
  • 18
  • 79
  • 144