- Use class keyword to define a class
- Use public keyword to define public member functions, which
indicate the operations can be performed on an object
- Use private keyword to define private data members, variables
that public member functions can access but are inaccessible outside the class
- Example Student class
class Student
{
// public member functions
public:
void SetName(string stuname)
{
name = stuname;
}
void SetGpa(double stugpa)
{
gpa = stugpa;
}
void Print()
{
cout << "Name: " << name << "\nGPA: " << gpa << endl;
}
// Private data members
private:
string name;
double gpa;
}; // Don't forget the semicolon!
- Declare a
Student
object
// s1 is a new Student
Student stu;
- Use the data member access operator (.) to call member functions
stu.SetName("Bob");
stu.SetGpa(3.0);
stu.Print();
- Private data members are not accessible outside the class
// WRONG - Syntax error!
stu.name = "Bob";
stu.gpa = 3.0;