The Class Construct
Aclass definition gives the data and the operations that apply to that data. The data can be
private, public or protected enabling data hiding and construction of Abstract
Data Types (ADTs).
An example of a simple class is given below:
#include <iostream.h>
#include <string.h>
class string {
char *str;
public:
string() // default constructor, takes
// no parameters
{
str = NULL;
}
string(const char *s)
// constructor with `char *' argument
{
str = new char [strlen(s) + 1];
strcpy(str,s);
}
string(const string& t)
// copy constructor, takes a reference
// to another string as the parameter
{
str = new char [strlen(t.str) + 1];
strcpy(str,t.str);
}
~string() // destructor
{
delete [] str;
}
void print() const
// print a string
{
cout << str;
}
};
int main()
{
string s1; // use default constructor
string s2("hello world");
// use constructor with `char *' argument
string s3(s2);
// use copy constructor
// print the strings
s1.print();
s2.print();
s3.print();
return 0;
}
Aclass definition gives the data and the operations that apply to that data. The data can be
private, public or protected enabling data hiding and construction of Abstract
Data Types (ADTs).
An example of a simple class is given below:
#include <iostream.h>
#include <string.h>
class string {
char *str;
public:
string() // default constructor, takes
// no parameters
{
str = NULL;
}
string(const char *s)
// constructor with `char *' argument
{
str = new char [strlen(s) + 1];
strcpy(str,s);
}
string(const string& t)
// copy constructor, takes a reference
// to another string as the parameter
{
str = new char [strlen(t.str) + 1];
strcpy(str,t.str);
}
~string() // destructor
{
delete [] str;
}
void print() const
// print a string
{
cout << str;
}
};
int main()
{
string s1; // use default constructor
string s2("hello world");
// use constructor with `char *' argument
string s3(s2);
// use copy constructor
// print the strings
s1.print();
s2.print();
s3.print();
return 0;
}
No comments:
Post a Comment