Index
Introduction
The scope resolution operator (::) in C++ is used to define and access something that is outside the current scope.
For example:
#include <iostream>
using namespace std;
class Rectangle {
private:
int length;
int breadth;
public:
// Constructor to initialize length and breadth
Rectangle(int l, int b) {
length = l;
breadth = b;
}
// Function to calculate area (declared inside the class)
int area();
// Function to calculate perimeter (defined inside the class)
int perimeter() {
return 2 * (length + breadth);
}
};
// Definition of the area function outside the class using scope resolution
int Rectangle::area() {
return length * breadth;
}
int main() {
// Create a Rectangle object
Rectangle rect(10, 5);
// Call the area function
cout << "Area of Rectangle: " << rect.area() << endl;
// Call the perimeter function
cout << "Perimeter of Rectangle: " << rect.perimeter() << endl;
return 0;
}
Output:
Area of Rectangle: 50
Perimeter of Rectangle: 30
Explanation:
Step 1: Include the Necessary Header:
#include <iostream>
using namespace std;- This includes the standard input/output stream library and allows the use of the
stdnamespace for convenience.
Step 2: Class Definition
class Rectangle {
private:
int length;
int breadth;
- Private Members:
lengthandbreadthare private data members, meaning they can only be accessed within theRectangleclass.
Step 3: Constructor
Rectangle(int l, int b) {
length = l;
breadth = b;
}
- Constructor: This constructor initializes the
lengthandbreadthwhen an object of theRectangleclass is created.
Step 4: Function Declarations:
int area();
int perimeter() {
return 2 * (length + breadth);
}
area()Function: Declared here but defined outside the class. The function calculates the area of the rectangle.perimeter()Function: Defined inside the class. It calculates the perimeter of the rectangle using the formula 2×(length+breadth).
Step 4: Definition of area() Function Using Scope Resolution:
int Rectangle::area() {
return length * breadth;
}
- Scope Resolution Operator (
::): This is used to define theareafunction outside the class. It tells the compiler that thisareafunction belongs to theRectangleclass.
Step 5: Main Function
int main() {
Rectangle rect(10, 5);
cout << "Area of Rectangle: " << rect.area() << endl;
cout << "Perimeter of Rectangle: " << rect.perimeter() << endl;
return 0;
}
- Create Object: An object
rectof theRectangleclass is created withlength = 10andbreadth = 5. - Call Functions:
rect.area() calculates and prints the area of the rectangle.
rect.perimeter() calculates and prints the perimeter of the rectangle.
Summary:
- Scope Resolution Operator (
::): Used to define thearea()function outside the class after it has been declared inside the class. - Constructor: Initializes the object’s
lengthandbreadth. - Member Functions:
area()andperimeter()calculate the rectangle’s area and perimeter, respectively.

