Create constructor for class to accept parameter and initialize objects - C++ Class

C++ examples for Class:Constructor

Description

Create constructor for class to accept parameter and initialize objects

Demo Code

#include <iostream>
#include <string>
class Course {/*from   www  .  j av a2 s  . co m*/
 private:
    std::string courseName;

 public:
    Course(std::string name) { setCourseName(name); }
    // SETTERS
    void setCourseName(std::string name) { courseName = name; }
    // GETTERS
    std::string getCourseName() { return courseName; }

    void displayMessage() {
        std::cout << "Welcome to the grade book for\n" << getCourseName() << "!" << std::endl;
    }
};

int main(int argc, const char *argv[]) {
    Course gradeBook1("Introduction to C++ Programming");
    Course gradeBook2("Data Structures in C++");

    // display initial value of courseName for each Course
    std::cout << "gradeBook1 created for course: "<< gradeBook1.getCourseName();
    std::cout << "\ngradeBook2 created for course: "<< gradeBook2.getCourseName() << std::endl;

    return 0;
}

Result


Related Tutorials