C++ Member Functions: Methods to Implement Class Behavior

What are Member Functions?

In C++, a class is a custom data type that can contain member variables (which describe an object’s properties) and member functions (which define an object’s behavior). Member functions act as the “behavior interface” of a class, determining what operations an object can perform. For example, a Person class might have name and age as member variables, while greet() is a member function that allows the object to “say hello.”

Defining Member Functions

Member functions can be defined inside the class (directly within the class’s curly braces) or outside the class (with the scope specified using “class name::”).

1. Defining Inside the Class (Most Common)

Declare and implement the function directly within the class:

class Person {
public:
    // Member variables: describe object properties
    string name;
    int age;

    // Member function: defines object behavior (greeting)
    void greet() {
        // Member functions can directly access class member variables
        cout << "Hello! I'm " << name << ", " << age << " years old." << endl;
    }
};

2. Defining Outside the Class (Requires Scope Specification)

If the function body is long, declare it inside the class and define it outside, specifying the class scope with class name:::

class Person {
public:
    string name;
    int age;
    void greet(); // Declaration inside the class
};

// Definition outside the class with scope Person::
void Person::greet() {
    cout << "Hello! I'm " << name << ", " << age << " years old." << endl;
}

How Member Functions Access Member Variables

Member functions can directly use the class’s member variables (no additional declarations needed). This is because every member function implicitly has a this pointer—a pointer that points to the object invoking the function. For example, this->name is equivalent to name (the compiler automatically adds this->).

Example:

Suppose we create two Person objects:

Person p1, p2;
p1.name = "Alice";
p1.age = 20;
p1.greet(); // Calls p1's greet()

p2.name = "Bob";
p2.age = 25;
p2.greet(); // Calls p2's greet()

Here, the this pointer points to p1 and p2 respectively, so greet() dynamically outputs different content based on the current object.

How to Call Member Functions

Member functions are called using the object syntax: object_name.function_name(). For pointers or references, use -> instead.

Example:

int main() {
    Person p;
    p.name = "Charlie";
    p.age = 30;
    p.greet(); // Output: Hello! I'm Charlie, 30 years old.
    return 0;
}

Special Member Functions

In addition to regular member functions, classes have special member functions for object initialization and cleanup:

1. Constructor

Automatically called when an object is created to initialize member variables. The constructor has the same name as the class and no return value:

class Person {
public:
    string name;
    int age;

    // Constructor: initializes name and age
    Person(string n, int a) {
        name = n;
        age = a;
    }

    void greet() {
        cout << "Hello! I'm " << name << ", " << age << " years old." << endl;
    }
};

// Using the constructor to create an object
Person p("David", 35); // Directly initializes name and age
p.greet(); // Output: Hello! I'm David, 35 years old.

2. Destructor

Automatically called when an object is destroyed to release resources (e.g., memory, file handles). The destructor name starts with “~” and has no parameters:

class Person {
public:
    ~Person() {
        cout << "Object destroyed; resources cleaned up!" << endl;
    }
};

Access Permissions for Member Functions

Member functions, like member variables, have access control (public/private/protected):
- public (Public): Accessible inside and outside the class; provides an interface.
- private (Private): Only accessible inside the class; hides implementation details.
- protected (Protected): Accessible inside the class and by derived classes (used for inheritance).

Example:

class Person {
private:
    string secret; // Private member variable

    void internalGreet() { // Private member function
        cout << "Secret: " << secret << endl;
    }

public:
    void setSecret(string s) {
        secret = s; // Public function can modify private variables
    }

    void publicGreet() {
        internalGreet(); // Public function can call private functions
    }
};

int main() {
    Person p;
    p.setSecret("I'm 200 years old!"); // Valid: call public function to set private variable
    p.publicGreet(); // Valid: call public function to access private function
    // p.internalGreet(); // Error: cannot directly call private function
    return 0;
}

Summary

Member functions are core to C++ classes:
1. They encapsulate “properties (member variables)” and “behavior” within a class, enabling objects to perform specific actions.
2. Called via object. function_name(), with the this pointer ensuring the function is bound to the object.
3. Constructors initialize objects, destructors clean up resources, and access modifiers (public/private) control access.

With an understanding of member functions, you can create complex objects with custom behaviors!

Xiaoye