a constructive exampleconsider an example to


A Constructive Example

Consider an example , to model a user-defined data type for  strings. The object simulates a character array ( string ) using a character pointer and an integer variable for its actual size, which can be explained at its run-time. The object doesn't use a character array , as it may impose a limit on the number of characters that can be stored.

e.g.

# include

# include < string.h>

class string

                 {

                  public :

                                string ( char *s);

                                ~string();

                                void putstr();

                  private :

                                char *cptr;

                                int size;

 };

void main(void)

                 {

                  string s1(" Hello student    \n");

                  string s2 = " Welcome to C++   \n";

                  string s3 = string ( " its fun \n");

 

s1.putstr();

                s2.putstr();

                s3.putstr();

 }

 

string::string(char *s)

                 {

                                size = strlen(s);

                                cptr = new char[size + 1];

                                strcpy(cptr,s);

                 }

string::~string()

                 {

                                delete cptr;

                 }

void string::putstr()

                 {

                                cout << cptr;

                 }

The class explained in the above example contains a character pointer, which allocates memory at run-time, after determining the actual size need. This programme demonstrates the use of class along with the constructor and destructor to make a user defined data type String. The constructor function contains a default argument of null character, which will be assigned to the variable cptr in the absence of an actual parameter. The destructor uses the delete operator to release the memory allocated by the constructor .

 

Request for Solution File

Ask an Expert for Answer!!
C/C++ Programming: a constructive exampleconsider an example to
Reference No:- TGS0309389

Expected delivery within 24 Hours