Class Methods in C++

Class methods are functions that are defined inside a class to perform some operation on the data member of the class.

A class method can be defined in two ways:

  1. Inside the class definition
  2. Outside the class definition

Defining Method inside the Class

In the example below, we created a class Product and defined a method getPrice() inside the class:


#include <iostream>
using namespace std;

class Product
{
public:
        double getPrice()
        { // This is the method
           return 700.56;
        }
};

// creating an object of the class
int main()
{
        Product product; // we create an object myobject
        double price = product.getPrice(); // calling the method
        cout<<"Product Price is : "<< price; 
        return 0;
}
Output
Product Price is : 700.56

Outside the class definition

Here, we define a method inside the class first and then define the same method outside the class. For that, we give the name of the class, followed by the operator :: then followed by the name of the method.

In the example below, we created a class Transaction and defined a method getAmount() outside the class.


#include <iostream>
using namespace std;

class Transaction
{
private:
        double amount = 0;

public:
        void setAmount(double amount);
        double getAmount();
};

//first method outsite class
void Transaction::setAmount(double amount)
{
        this->amount = amount;
}

// second method outside class
double Transaction::getAmount()
{
        return this->amount;
}

// creating an object of the class
int main()
{
        Transaction transaction;                 // creating an object
        transaction.setAmount(240);              // setting amount
        double amount = transaction.getAmount(); // getting amount
        cout << "The transaction amount is : " << amount;
        return 0;
}
Output
The transaction amount is : 240