Variables and functions that are defined inside a class are called class attributes and methods. They are often collectively referred to as the class.
Consider the following illustration to comprehend what class attributes are
#include <iostream>
using namespace std;
class Employee
{
int eID;
string eName;
public:
};
int main()
{
Employee Harry;
}
Two members, eId and eName, are defined inside the Employee class, which is created. These two individuals are class characteristics since they are variables. Harry is now specified as an object in the main. Harry can use the dot operator to retrieve these characteristics. But unless they are made public, Harry cannot access them.
class Employee
{
public:
int eID;
string eName;
};
int main()
{
Employee Harry;
Harry.eID = 5;
Harry.eName = "Harry";
cout << "Employee having ID " << Harry.eID << " is " << Harry.eName << endl;
}
Output:
Employee having ID 5 is Harry
Class methods are simply functions that have been specified in or are a part of a class. The same way that objects access attributes, so do the methods that belong to a class. There are two ways to define a function so that it is a member of a class.
Defining inside the class
An illustration of how to define functions inside of classes is
class Employee
{
public:
int eID;
string eName;
void printName()
{
cout << eName << endl;
}
};
Defining outside the class
A function must be declared inside the class even though it can be defined outside of it. Later, we can define the function outside using the scope resolution operator (::). An illustration of how to define functions outside of classes is
class Employee
{
public:
int eID;
string eName;
void printName();
};
void Employee::printName()
{
cout << eName << endl;
}