Book Class 2
2002-05-16 22:27:12
Category: cpp:classes
Description: The same as the Book class with the addition of a deconstructor and a constructor.
Author: detour
Viewed: 2664
Rating: (6 votes)


/* bkClass2.cpp by detour@metalshell.com
 *
 * bkClass.cpp with the addition of a constructor
 * and deconstructor.
 *
 * http://www.metalshell.com/
 *
 */
 
#include <string>
#include <iostream>
 
class Book {
    private:
        int pages;
        /* If you use dynamic memory you'll need
           a deconstructor to free it */
        char *Author;
        char ISBN[14];
    public:
        /* A constructor that takes no args, it is
           called everytime an instance of the class
           is made.  Initial data is set in the 
           constructor.  */
        Book() {
            pages = 0;
            strcpy(ISBN, "F-FFF-FFFFF-F");
            Author = NULL;
        }
        /* Overloaded constructor that takes all the data
           when it is created */
        Book(char *nISBN, int npages, char *nAuthor) {
            setPages(npages);
            setISBN(nISBN);
            setAuthor(nAuthor);
        }
        /* The deconstructor is called when the object
           goes out of scope */
        ~Book() {
            delete Author;
        }
        void setISBN(char *nISBN) {
            if(strlen(nISBN) < 14)
                strcpy(ISBN, nISBN);
        }
        void setPages(int npages) {
            pages = npages;
        }
        void setAuthor(char *nAuthor) {
            Author = new char[strlen(nAuthor)+1];
            strcpy(Author,nAuthor);
        }
        void displayData() {
            cout << "********  Book  ********\n";
            if(Author != NULL)
                cout << "* Author: " << Author << endl;
            cout << "* ISBN:   " << ISBN << endl;
            cout << "* Pages:  " << pages << endl;
            cout << "************************\n";
        }
};
 
int main() {
    /* Constructor with no args is called */
    Book myBook;
    /* Constructor that takes everything is called */
    Book myBook2("0-451-16953-0", 1138, "Stephen King");
 
    myBook.setISBN("0-671-04191-6");
    myBook.setPages(296);
    myBook.setAuthor("Art Bell");
    myBook.displayData();
 
    myBook2.displayData();
 
    return 0;
}