



(9 votes)/* bkClass.cpp by detour@metalshell.com * * Very basic example of a class * * http://www.metalshell.com/ * */ #include <string> #include <iostream> class Book { /* Private members of a class can never be altered by anything but functions of the class. The data is considered hidden. */ private: int pages; char ISBN[14]; /* All the functions needed to be called from outside the class are declared as public. */ public: /* Becuase only functions in the class can modify the data you need to have set functions. Always perform your checks for valid data in these functions. */ void setISBN(char *nISBN) { if(strlen(nISBN) < 14) strcpy(ISBN, nISBN); } void setPages(int npages) { pages = npages; } /* A print out of the data */ void displayData() { cout << "******* Book *******\n"; cout << "* ISBN: " << ISBN << endl; cout << "* Pages: " << pages << endl; cout << "**********************\n"; } }; int main() { Book myBook; myBook.setISBN("0-671-04191-6"); myBook.setPages(296); myBook.displayData(); /* These would not work becuase you can not read or modified private data */ // cout << myBook.ISBN; // pages = 500; return 0; }