C++ Class Methods

In C++, class methods are functions that are associated with a class and operate on its data members. They are also known as member functions. Class methods can be divided into two main categories: instance methods and static methods.

Here's an overview of instance methods and static methods:

  1. Instance Methods:
  2. Instance methods are associated with objects of the class. They can access and modify the instance-specific (non-static) members of the class. In C++, instance methods are declared within the class definition and defined outside of it.

    Example of declaring and defining an instance method:

    class MyClass {
    public:
        void instanceMethod() {
            // Method definition
        }
    };
    
    // Outside the class, define the instance method
    void MyClass::instanceMethod() {
        // Implementation of the method
    }

    To use an instance method:

    MyClass obj;
    obj.instanceMethod(); // Calling the instance method on the object

    Here's a simple example to demonstrate how instance methods can be used to perform actions specific to each instance (object) of a class:

    #include <iostream>
    #include <string>
    
    class Student
    {
    private:
        std::string name;
        int age;
    
    public:
        // Constructor to initialize the object
        Student(const std::string &n, int a) : name(n), age(a) {}
    
        // Instance method to display student information
        void displayInfo()
        {
            std::cout << "Name: " << name << std::endl;
            std::cout << "Age: " << age << std::endl;
        }
    
        // Instance method to enroll the student in a course
        void enroll(const std::string &courseName)
        {
            std::cout << name << " is now enrolled in the course " << courseName << std::endl;
        }
    };
    
    int main()
    {
        // Creating instances of the Student class
        Student student1("Jake", 34);
        Student student2("Ryan", 32);
    
        // Using instance methods to display information and enroll students
        student1.displayInfo();
        student1.enroll("Mathematics");
    
        student2.displayInfo();
        student2.enroll("Computer Science");
    
        return 0;
    }

    In this example, we have a Student class with two instance methods: displayInfo and enroll. The displayInfo method displays the student's name and age, while the enroll method enrolls the student in a specific course. We create two instances of the Student class (student1 and student2) and use their respective instance methods to display information and enroll them in courses.

    The output of the above code is as follows:

    Name: Jake
    Age: 34
    Alice is now enrolled in the course Mathematics
    Name: Ryan
    Age: 32
    Bob is now enrolled in the course Computer Science
  3. Static Methods:
  4. Static methods are associated with the class itself, not with instances of the class. They cannot access instance-specific members (non-static members) directly but can access static members and other static methods. Static methods are declared with the static keyword and are defined outside the class definition.

    Example of declaring and defining a static method:

    class MyClass {
    public:
        static void staticMethod() {
            // Method definition
        }
    };
    
    // Outside the class, define the static method
    void MyClass::staticMethod() {
        // Implementation of the method
    }

    To use a static method:

    MyClass::staticMethod(); // Call the static method on the class itself

    Here's a simple example to demonstrate how static methods can be used to perform class-specific actions:

    #include <iostream>
    
    class Calculator {
    public:
        // Method to add two numbers
        static int add(int a, int b) {
            return a + b;
        }
    
        // Method to subtract two numbers
        static int subtract(int a, int b) {
            return a - b;
        }
    };
    
    int main() {
        int num1 = 20;
        int num2 = 9;
    
        // Using the Calculator class to perform addition and subtraction
        int sum = Calculator::add(num1, num2);
        int difference = Calculator::subtract(num1, num2);
    
        std::cout << "Sum: " << sum << std::endl;
        std::cout << "Difference: " << difference << std::endl;
    
        return 0;
    }

    In this example, the Calculator class has two static methods, add and subtract. These methods take two integer arguments and perform addition and subtraction, respectively. In the main function, we use the Calculator class to perform addition and subtraction on two integer values and then display the results.

    The output of the above code is as follows:

    Sum: 29
    Difference: 11

In addition to instance and static methods, C++ supports various access specifiers (public, private, and protected) to control the visibility and accessibility of class members. Instance methods and instance data members are often placed in the public section of a class to allow access from outside the class, while static methods and static data members are declared in the public section and can be accessed using the class name.

This example will demonstrate how access specifiers are used to control the visibility and accessibility of methods in a practical context:

#include <iostream>
#include <string>

class BankAccount {
public:
    // Public instance method to check the account balance
    double getBalance() const {
        return balance;
    }

    // Public instance method to make a deposit
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            std::cout << "Deposited $" << amount << ". New balance: $" << balance << std::endl;
        } else {
            std::cout << "Invalid deposit amount." << std::endl;
        }
    }

    // Public instance method to make a withdrawal
    bool withdraw(double amount) {
        if (amount > 0 && balance >= amount) {
            balance -= amount;
            std::cout << "Withdrawn $" << amount << ". New balance: $" << balance << std::endl;
            return true;
        } else {
            std::cout << "Invalid withdrawal amount or insufficient balance." << std::endl;
            return false;
        }
    }

protected:
    // Protected instance method to calculate interest
    void calculateInterest() {
        // In a real-world scenario, this method might perform complex interest calculations
        // For simplicity, let's assume a fixed interest rate of 2% per month.
        balance += balance * 0.02;
        std::cout << "Interest calculated. New balance: $" << balance << std::endl;
    }

private:
    std::string accountNumber;
    double balance;

public:
    // Public static method to create a new bank account
    static BankAccount createAccount(const std::string& accountNumber, double initialBalance) {
        BankAccount newAccount;
        newAccount.accountNumber = accountNumber;
        newAccount.balance = initialBalance;
        return newAccount;
    }
};

int main() {
    // Creating a bank account using the static method
    BankAccount account1 = BankAccount::createAccount("123456789", 1000.0);

    // Accessing public methods
    std::cout << "Account 1 Balance: $" << account1.getBalance() << std::endl;
    account1.deposit(500.0);
    account1.withdraw(200.0);

    // Accessing protected method (This line will generate a compilation error)
    // account1.calculateInterest();

    return 0;
}

In this example, Public instance methods (getBalance, deposit, withdraw) can be accessed from outside the class as well as within the class. They allow users to check balances, deposit, and withdraw funds. The protected instance method calculateInterest is used for interest calculations, which are typically considered an internal operation and are not meant to be called directly by external users. In this example, we have included a placeholder for interest calculation. Private data members (accountNumber and balance) and private methods (calculateInterest) are not accessible outside the class. These represent internal details of the bank account class. The public static method createAccount is used to create a new bank account and initialize its attributes. Static methods are associated with the class itself and not with instances of the class. In the main function, we create a bank account object, access its public methods, and demonstrate the restricted access to protected methods. Private members and methods cannot be accessed from outside the class.

The output of the above class is as follows:

Account 1 Balance: $1000
Deposited $500. New balance: $1500
Withdrawn $200. New balance: $1300