Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Class Methods

Class Method

Class methods, also known as member functions in C++, are functions defined within a class that operate on the class’s data members (attributes) and perform specific tasks associated with the class. Here’s how you define and use class methods in C++:

#include <iostream>
using namespace std;

class MyClass {         // The class
  public:               // Access specifier
    void Method() {   // Method/function
      cout << "Some text";
    }
};

int main() {
  MyClass Obj;     // Create an object of MyClass
  Obj.Method();  // Call the method
  return 0;
}

Output:

Some text

Parameters

You also add parameters of different types:

Example:

#include <iostream>
using namespace std;

class Car {
  public:
    int speed(int minSpeed);
};

int Car::speed(int minSpeed) {
  return minSpeed;
}

int main() {
  Car myObj;
  cout << myObj.speed(100);
  return 0;
}

Output:

100

    Leave a Reply

    Your email address will not be published.

    Need Help?