Constructor
A
constructor is basically a function used for initialization of the class data
members, allocation of memory, and so on. It is convenient if an object can
initialize itself when it is first created, without the need to make a separate
call to a member function. It has the same name as the class in which they are
members. No return type is used for constructors. Since the constructor is
called automatically by the system there is no reason for it to return
anything. Compiler knows that they are constructors by looking at their name
and return type. Let us take an example that each time an object of the date
class is created, it is to be initialized with the date 2/02/2011.
Examples:
class date{
private:
int dd,yy;
char mm[3];
public:
date() //
constructor
{
dd=2,mm[0]='0',mm[1]='2';
mm[2]='\0',
yy=2011;
}
showdate()
//display
{
cout<<"\n"<<dd<<"/"<<mm<<"/"<<yy;
}
};
int main()
{
date d1;
//define and initialize
clrscr();
d1.showdate();
return 0;
}
Write a
program that has a class to represent time. The class should have constructors
to initialize data members hour, minute and second to 0 and to initialize them
to values passed as arguments. The class should have member function to add
time objects and return the result as time object. There should be another
function to display the result in 24 hour format
Write a
program that has a class with a dynamically allocated character array as its
data member. One object should contain "Engineers are" and another
should contain " Creatures of logic". Member function join() should
concatenate two strings by passing two objects as arguments. Display the
concatenated string through a member function. Use constructors to allocate and
initialize the data member. Also, write a destructor to free the allocated
memory for the character array. Make your own function for concatenation of two
strings.
No comments:
Post a Comment