ex4-10.cpp - Example 4-10 Multiple constructors - the text class

// File: ex4-10.cpp

#include <iostream>
#include <cstring>
using namespace std;

class text
{
private:
    char* s;
    int length;
public:
    text(void); // default constructor
    text(const char *);
    text(const text&); // copy constructor
    text(int);
    text(char);

    ~text()       // inline destructor
    {
        delete [] s;
    };
    void print(void) const;
};

text::text(void) // default constructor
{
    s = new char[1];
    s[0] = '\0';
    length = 0;
}

text::text(const char* str)
{
    s = new char[strlen(str) + 1];
    length = strlen(str);
    strcpy(s, str);
}

text::text(const text& str)
{
    length = str.length;
    s = new char[length + 1];
    strcpy(s, str.s);
}

text::text(int len)
{
    length = len;
    s = new char[length + 1];
}

text::text(char ch)
{
    length = 1;
    s = new char[2];
    s[0] = ch;
    s[1] = '\0';
}

void text::print(void) const
{
    cout << s << endl;
}

int main(void)
{
    text a("Have a nice day");
    a.print();

    text b(a);
    b.print();

    text c;
    c.print();

    text d(15);
    d.print();

    text e('x');
    e.print();

    return 0;
}



CIS27: Programming in C++    Instructor: Joe Bentley