C++ Class Methods
Last Updated :
19 Jan, 2023
Prerequisite: Class in C++
Class is a blueprint of an object, which has data members and member functions also known as methods. A method is a procedure or function in the oops concept. A method is a function that belongs to a class.
There are two ways to define a procedure or function that belongs to a class:
- Inside Class Definition
- Outside Class Definition
1. Inside Class Definition
The member function is defined inside the class definition it can be defined directly. Similar to accessing a data member in the class we can also access the public member functions through the class object using the dot operator (.).
Syntax:
class class_name{
public:
return_type Method_name() // method inside class definition
{
// body of member function
}
};
Example:
C++
#include <iostream>
using namespace std;
class rectangle {
private :
int length;
int breadth;
public :
rectangle( int length, int breadth)
{
this ->length = length;
this ->breadth = breadth;
}
int area() { return (length * breadth); }
int perimeter() { return 2 * (length + breadth); }
};
int main()
{
rectangle r(2, 3);
cout << "perimeter: " << r.perimeter() << endl;
cout << "area: " << r.area() << endl;
return 0;
}
|
Output
perimeter: 10
area: 6
2. Outside Class Definition
The member function is defined outside the class definition it can be defined using the scope resolution operator. Similar to accessing a data member in the class we can also access the public member functions through the class object using the dot operator (.).
Syntax:
class Class_name{
public:
return_type Method_name(); // method outside class definition
};
// Outside the Class using scope resolution operator
return_type Class_name :: Method_name() {
// body of member function
}
Example: In the following code, a rectangle class, in which member function area() and member function perimeter() is defined outside the class by using the scope resolution operator.
C++
#include <iostream>
using namespace std;
class rectangle {
private :
int length;
int breadth;
public :
rectangle( int length, int breadth)
{
this ->length = length;
this ->breadth = breadth;
}
int area();
int perimeter();
};
int rectangle::area() { return (length * breadth); }
int rectangle::perimeter()
{
return 2 * (length + breadth);
}
int main()
{
rectangle r(2, 3);
cout << "perimeter: " << r.perimeter() << endl;
cout << "area: " << r.area() << endl;
return 0;
}
|
Output
perimeter: 10
area: 6
Share your thoughts in the comments
Please Login to comment...