C++ Class Methods C-PLUS-PLUS
- C++ Introduction
- C++ Syntax
- C++ Output (cout <<)
- C++ Comments
- C++ Variables
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ If Else
- C++ Switch
- C++ While Loop
- C++ Do/While Loop
- C++ For Loop
- C++ Break and Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Functions Parameters
- C++ Function Overloading
- C++ OOP
- C++ Classes and Objects
- C++ Class Methods
- C++ Constructors
- Destructors in C++
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Polymorphism
- C++ Files
- C++ Exception Handling
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!