C++ Class Methods C-PLUS-PLUS

C++ Class Methods  

C++ Class Methods

C++ Class Methods

Methods are functions that belong to the class.

There are two ways to define functions that belong to a class:

  • Inside class definition
  • Outside class definition

And You access methods just like you access attributes, by creating an object of the class and by using the dot syntax (.) you can call methods or functions.

Inside Class Example

#include <iostream>
using namespace std;

class MyClass {           // The class
  public:                        // Access specifier
    void myMethod() {   // Method/function
      cout << "Hello World!";
    }
};

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

Output:

Hello World!

C++ Methods Outside The Class

To define a function outside the class definition, you have to declare it inside the class and then define it outside of the class. This is done by specifying the name of the class, followed the scope resolution :: operator, followed by the name of the function.

Example

#include <iostream>
using namespace std;

class MyClass {         // The class
  public:                      // Access specifier
    void myMethod();   // Method/function declaration
};

// Method/function definition outside the class
void MyClass::myMethod() {
  cout << "Hello World!";
}

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

Output:

Hello World!

Download free E-book of C-PLUS-PLUS


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries