class Student { public: void SetName(string name); string GetName(); void Print(); private: string name = "John Doe"; char gender = 'M'; double gpa = 0; }; int main() { Student s; s.Print(); // John Doe, M, 0 }
class Student { public: Student(); // default constructor declaration ... private: string name; char gender; double gpa; }; // default constructor definition Student::Student() { name = "John Doe"; gender = 'M'; gpa = 0.0; }
Student s; // Default constructor is called s.Print(); // John Doe, M, 0
class ClassName { public: // Overloaded constructor ClassName(type1 param1, type2 param2, etc.) { // Set member1, member2, etc. to param1, param2, etc. } private: type1 member1; type2 member2; }
Student
class Student { public: Student(string name, char gender, double gpa); ... private: string name; char gender; double gpa; }; // Overloaded constructor Student::Student(string name, char gender, double gpa) { this->name = name; this->gender = gender; this->gpa = gpa; }
this->name
is the member name)
// Calls the constructor Student s("Bob", 'M', 3.0);
// Call constructor explicitly s = Student("Sue", 'F', 3.5);
// Constructor Student::Student(string name, char gender, double gpa) { this->name = name; // Ensure gender is M or F this->gender = toupper(gender); if (gender != 'M' && gender != 'F') this->gender = '?'; // Ensure gpa is between 0 and 4 if (gpa < 0) this->gpa = 0; else if (gpa > 4) this->gpa = 4; else this->gpa = gpa; }
class Student { public: // gender and gpa given default values Student(string name, char gender = '?', double gpa = 0); ... private: string name; char gender; double gpa; }; int main() { Student s1("Bob"); // gender is '?', gpa is 0 Student s2("Pam", 'F'); // gpa is 0 Student s3("Jim", 'M', 3.4); // No default values used }
class Student { public: // All parameters have default values Student(string name = "No Name", char gender = '?', double gpa = 0); ... }; int main() { // name = "No Name", gender = '?', gpa = 0 Student stu; }
ClassName(type1 param1, type2 param2) : attr1(param1), attr2(param2) { }
Student
constructor
// Default constructor Student() : name("John Doe"), gender('M'), gpa(2.0) { } // Overloaded constructor Student(string name, char gender, double gpa) : name(name), gender(gender), gpa(gpa) { }