Page 165 - DCAP404 _Object Oriented Programming
P. 165
Object-oriented Programming
Notes strcpy(name,a);
}
This constructor builds a string type object from a char* type variable a. The variables length and
name are data members of the class string. Once you define the constructor in the class string, it
can be used for conversion from char* type to string type.
Example:
string s1, s2;
char* name1 = “Good Morning”;
char* name2 = “STUDENTS” ;
s1 = string(name1);
s2 = name2;
The program statement
s1 = string (name1);
first converts name1 from char* type to string type and then assigns the string type values to the
object s1. The statement
s2 = name2;
performs the same job by invoking the constructor implicitly.
Consider the following example
class time
{
int hours;
int minutes;
public:
time (int t) II constructor
{
hours = t / 60; //t is inputted in minutes
minutes = t % 60; .
}
};
In the following conversion statements:
time T1; //object T1 created
int period = 160;
T1 = period; //int to class type
The object T1 is created. The variable period of data type integer is converted into class type time
by invoking the constructor. After this conversion, the data member hours of T1 will have value
2 arid minutes will have a value of 40 denoting 2 hours and 40 minutes.
158 LOVELY PROFESSIONAL UNIVERSITY