Introduction to C++ Classes and Objects: Defining a Simple Class

Concepts of Class and Object

Imagine you want to build a “robot” to help with daily tasks. This robot needs its own “physical characteristics” (like name, battery level) and “abilities” (like walking, talking). In programming, we call these “physical characteristics” member variables (attributes) and “abilities” member functions (methods). The “robot” itself is an instance of the “class” we’re discussing—this is the object.

In simple terms, a class is an abstract description of a type of thing, defining what it has (attributes) and what it can do (behaviors). An object is a concrete “individual” created based on this description. In C++, we use the class keyword to define a class, then create objects from this class to use its member variables and functions.

Syntax for Defining a Class in C++

The basic format for defining a class is as follows:

class ClassName {
    // Member variables (attributes): Describe object characteristics, usually set to private for security
private:
    Data_Type VariableName1;
    Data_Type VariableName2;
    // ... other member variables

    // Member functions (methods): Describe object behaviors, usually set to public for external access
public:
    // Declaration of member functions (e.g., set/get variables, perform actions)
    Return_Type FunctionName1(Parameter_List) {
        // Function body: Implement the behavior
    }
    Return_Type FunctionName2(Parameter_List) {
        // ...
    }
    // ... other member functions
};
  • class keyword: Used to declare a class.
  • private and public: Access modifiers. private members can only be accessed within the class, while public members can be directly accessed by code outside the class.
  • Semicolon: A semicolon is required at the end of the class definition (syntax requirement).

Defining a Simple “Student” Class

Let’s define a “Student” class that includes basic student information and behaviors.

Step 1: Define the Class Structure

Assume a student has two core attributes: name and student ID, plus two behaviors: studying and self-introducing.

class Student {
private:  // Private members: Not directly accessible externally, ensuring data security
    string name;  // Name (string type)
    int id;       // Student ID (integer type)

public:   // Public members: Functions accessible directly from outside
    // Function to set the name (parameter: name to set)
    void setName(string n) {
        name = n;  // Assign the parameter to the member variable 'name'
    }

    // Function to get the name (return value: current name)
    string getName() {
        return name;  // Return the value of the member variable 'name'
    }

    // Function to set the student ID (parameter: ID to set)
    void setId(int i) {
        id = i;  // Assign the parameter to the member variable 'id'
    }

    // Self-introduction function: Outputs the student's name and ID
    void introduce() {
        cout << "Hello everyone! My name is " << name << ", and my student ID is " << id << "." << endl;
    }

    // Study function: Outputs the student's learning activity
    void study() {
        cout << name << " is diligently studying C++!" << endl;
    }
};

Creating Objects and Using the Class

After defining the class, we need to create an object (a specific student instance) and call the class’s member functions through this object.

Step 2: Using the Student Class in main()

#include <iostream>
#include <string>  // Required for string type
using namespace std;  // Simplify code (no need to write std::)

int main() {
    // 1. Create an object of the Student class, named stu1
    Student stu1;

    // 2. Set the student's name and ID (via public member functions)
    stu1.setName("Zhang San");  // Call setName with the name
    stu1.setId(2023001);        // Call setId with the student ID

    // 3. Call member functions
    stu1.introduce();  // Output self-introduction
    stu1.study();      // Output learning activity

    return 0;
}

Output Result

When you compile and run the code above, the output will be:

Hello everyone! My name is Zhang San, and my student ID is 2023001.
Zhang San is diligently studying C++!

Key Knowledge Summary

  1. Class Definition: Use the class keyword, containing private member variables (via private) and public member functions (via public).
  2. Object Creation: ClassName ObjectName; (e.g., Student stu1;).
  3. Member Access: Objects call public functions using ObjectName.FunctionName() (e.g., stu1.study()), and member variables are accessed indirectly via set/get functions (e.g., stu1.setName()).
  4. Encapsulation Idea: Member variables are set to private and only accessible via public functions, preventing external direct modification and ensuring data security.

With this simple example, you’ve mastered the basics of C++ classes and objects: how to define a class, create objects, and call member functions. In the future, you can extend the class’s functionality (e.g., add attributes like age or grades, or more behaviors) and explore concepts like encapsulation and inheritance.

Xiaoye