C++ member functions
Created By: chatGPT
Member functions in C++ are functions that are defined within a class and can operate on the class's data members. They allow objects of the class to perform actions and interact with their data. In this tutorial, we will explore how to define and use member functions with examples.
class MyClass {
private:
int value;
public:
// Constructor
MyClass(int v) : value(v) {}
// Member function to get the value
int getValue() {
return value;
}
// Member function to set the value
void setValue(int v) {
value = v;
}
};
Defining Member Functions: Member functions are defined inside the class declaration. You can also define them outside the class using the scope resolution operator
::
.void MyClass::setValue(int v) {
value = v;
}
Access Specifiers: Member functions can use public, protected, and private access specifiers to control access to the class's data members. Public member functions can be accessed from outside the class, while private member functions cannot.
class MyClass {
private:
int value;
public:
void displayValue() {
std::cout << "Value: " << value << std::endl;
}
};
Const Member Functions: If a member function does not modify the object's state, you can declare it as
const
. This tells the compiler that the function will not change any member variables.class MyClass {
private:
int value;
public:
MyClass(int v) : value(v) {}
int getValue() const {
return value;
}
};
Static Member Functions: These functions belong to the class rather than any specific object. They can only access static data members or other static member functions. Here’s how to declare and define a static member function.
class MyClass {
private:
static int count;
public:
static void incrementCount() {
count++;
}
};
int MyClass::count = 0;
Using Member Functions: You can create an object of the class and call member functions using the dot
.
operator. Here’s a quick example to demonstrate usage.int main() {
MyClass obj(10);
std::cout << obj.getValue() << std::endl; // Output: 10
obj.setValue(20);
obj.displayValue(); // Output: Value: 20
return 0;
}