Anatomy of a class Part I CSCE 121 J. Michael Moore Based on Slides created by Carlos Soto.
Classes in C++ User-defined datatypes Data members (aka attributes) Variables that are instances of a class datatype are called objects Data members (aka attributes) Can be any datatype Including other classes Member functions (aka methods) Act with or upon the object used to call the method
Visibility Private Public Can only be accessed from within the class Commonly used for most data members Default for C++ classes Public Can be accessed inside or outside the class Commonly used for user-facing functions Make up the class’s interface Default for C++ structs
Class names are capitalized by convention. Writing a class class Student { }; Class names are capitalized by convention.
Writing a class: public and private member access class Student { private: // data members and member functions public: // ... }; Class names are capitalized by convention.
Writing a class: attributes / data members class Student { private: string name; int id; double grade; char letterGrade; public: // data members and member functions };
Writing a class: mutators and accessors / setters and getters class Student { private: string name; int id; double grade; char letterGrade; public: string getName (); void setName (string name); // ... }; Note: member functions are declared, not defined.
Writing a class: function definitions/declarations class Student { string name; // ... public: string getName () { return name; } void setName (string name) { name = name; }; This does not work. Parameter name hides class name. Which name is which???
Writing a class: using ‘implicit’ this parameter class Student { string name; // ... public: string getName () void setName (string name) }; ‘this’ indicates the one that belongs to the class. { return name; } this->name = name; Alternatively you could give them different names. Some will add an underscore to the beginning of one of them. E.g. _name
Writing a class: function definition outside class definition class Student { string name; // ... public: string getName (); void setName (string name); }; string Student::getName () { return name; } Scope Resolution Operator
Using a class Declare/define variable just like any other datatype. class Student { // ... public: string getName(); void setName(string name); }; int main() { Student joe; joe.setName(“Joe Smith”); string name = joe.getName(); } Declare/define variable just like any other datatype. Access attributes/methods with . (dot) operator. Just like using vectors.
Classes & Structs: default visibility class MyClass { // members are private by default }; struct MyStruct { // members are public by default