C++ examples for Class:Class Creation
Define class public interface of the class.
#include <string> // ww w. j a va2s . co m class Course { private: std::string courseName; public: Course(std::string); // SETTERS void setCourseName(std::string); // GETTERS std::string getCourseName(); void displayMessage(); }; #include <iostream> Course::Course(std::string name) { setCourseName(name); } // SETTERS // ensure coursename does not exceed 25 chars void Course::setCourseName(std::string name) { if (name.length() <= 25) courseName = name; if (name.length() > 25) { courseName = name.substr(0, 25); std::cout << "Name \"" << name << "\" exceeds maximum length (25).\n"; std::cout << "Limiting courseName to first 25 characters.\n" << std::endl; } } // GETTERS std::string Course::getCourseName() { return courseName; } // display a welcome message to the Course user void Course::displayMessage() { std::cout << "Welcome to the grade book for\n" << getCourseName() << "!" << std::endl; } int main(int argc, const char *argv[]) { Course gradeBook1("C++"); Course gradeBook2("Java"); std::cout << "gradeBook1 initial course name: " << gradeBook1.getCourseName(); std::cout << "\ngradeBook2 initial course name: " << gradeBook2.getCourseName() << std::endl; // modify myCourse's courseName (with a valid length string) gradeBook1.setCourseName("Python"); // display each Course's courseName std::cout << "\ngradeBook1 course name: " << gradeBook1.getCourseName(); std::cout << "\ngradeBook2 course name: " << gradeBook2.getCourseName() << std::endl; return 0; }