A Class is Building block in C++ which holds its own Data Members, Functions, and Methods , which can be accessed by creating a Class. For Example, Car is a Class and Properties will be 4 Wheels, Speed Limit, Mileage etc.
Syntax of Class:
ClassName ObjectName;
Class Methods:
Methods are the functions that Belong to the Class.
There are 2 ways to define a member function
Inside Class Definition
Outside Class Definition
1. INSIDE CLASS DEFINITION:
#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;
}
2. OUTSIDE CLASS DEFINITION: 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:
#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;
}
resources: W3school
The Tech Platform
Comments