C++ Class Methods
Class methods are functions that are defined within a class and operate on the class's data members. They can be used to manipulate the object's state or perform operations related to the object.
Key Topics
1. Types of Methods
There are several types of methods in C++ classes:
- Instance Methods: Operate on instances of the class and can access instance variables.
- Static Methods: Belong to the class itself rather than any object and cannot access instance variables.
- Const Methods: Do not modify the object and are declared with the
const
keyword.
2. Defining Methods
Methods are defined inside the class definition or outside using the scope resolution operator ::
.
Example: Defining Instance and Static Methods
class Car {
public:
std::string brand;
std::string model;
int year;
void displayInfo() {
std::cout << brand << " " << model << " " << year << std::endl;
}
static void showType() {
std::cout << "This is a car." << std::endl;
}
};
Code Explanation: The displayInfo
method is an instance method, while showType
is a static method that can be called without an object.
3. Accessing Methods
Methods can be accessed using the object of the class or directly using the class name for static methods.
Example: Accessing Methods
int main() {
Car myCar;
myCar.brand = "Toyota";
myCar.model = "Corolla";
myCar.year = 2020;
myCar.displayInfo(); // Calls instance method
Car::showType(); // Calls static method
return 0;
}
Output:
This is a car.
Code Explanation: The instance method displayInfo
is called on the object myCar
, which prints the car's details, while the static method showType
is called using the class name Car
.
Key Takeaways
- Class methods are essential for defining the behavior of objects.
- Instance methods can access and modify instance variables, while static methods cannot.
- Understanding how to define and access methods is crucial for effective object-oriented programming in C++.