Add more fields, getter and setter methods to a class - C++ Class

C++ examples for Class:Class Creation

Description

Add more fields, getter and setter methods to a class

Demo Code

                  
#include <string>
                  //from w  ww.  j  av a  2 s  . co m
class Course {
 private:
    std::string courseName;
    std::string instructorName;
                  
 public:
    Course(std::string, std::string);
                  
    // SETTERS
    void setCourseName(std::string);
    void setInstructorName(std::string);
                  
    // GETTERS
    std::string getCourseName();
    std::string getInstructorName();
                  
    void displayMessage();
};
#include <iostream>
                  
// Constructor
Course::Course(std::string name, std::string instructor) {
    setCourseName(name);
    setInstructorName(instructor);
}
// SETTERS
void Course::setCourseName(std::string name) { courseName = name; }
void Course::setInstructorName(std::string instructor) {
    instructorName = instructor;
}
// GETTERS
                  
std::string Course::getCourseName() { return courseName; }
std::string Course::getInstructorName() { return instructorName; }
                  
// display a welcome message to the Course user
void Course::displayMessage() {
    std::cout << "Welcome to the grade book for\n" << getCourseName() << "!" << std::endl;
    std::cout << "This course is presented by: " << getInstructorName() << std::endl;
}
int main(int argc, const char *argv[]) {
    Course gradeBook1("This is a course", "The Instructor");
                  
    gradeBook1.displayMessage();
                  
    return 0;
}

Result


Related Tutorials