Scope Resolution in C++
Scope Resolution in C++
The scope resolution operator (`::`) in C++ is used to access members (variables, functions, or classes)
that belong to a specific scope. It helps resolve ambiguity when multiple scopes have elements with the
same name.
cpp
#include <iostream>
using namespace std;
int x = 10; // Global variable
class Test {
public:
int x = 20; // Member variable
void show() {
cout << "Local x: " << x << endl;
cout << "Global x: " << ::x << endl; // Accessing global x
}
};
int main() {
Test obj;
obj.show();
return 0;
}
Output:
sql
Local x: 20
Global x: 10
cpp
class Demo {
public:
void show(); // Function prototype
};
int main() {
Demo obj;
obj.show();
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/5
return 0;
}
cpp
class Sample {
public:
static int count;
};
int main() {
cout << "Static count: " << Sample::count << endl;
return 0;
}
Output:
scss
cpp
class A {
public:
void show() { cout << "Class A" << endl; }
};
class B {
public:
void show() { cout << "Class B" << endl; }
};
int main() {
C obj;
obj.display();
return 0;
}
Output:
css
Class A
Class B
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/5
cpp
#include <iostream>
namespace ns {
int x = 50;
}
int main() {
cout << "Namespace x: " << ns::x << endl;
return 0;
}
Output:
vbnet
Namespace x: 50
Thus, the scope resolution operator (`::`) helps access specific elements across different scopes,
prevents ambiguity, and ensures better code organization.
cpp
#include <iostream>
using namespace std;
class Shallow {
public:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/5
int* ptr;
// Constructor
Shallow(int val) {
ptr = new int(val);
}
// Destructor
~Shallow() {
delete ptr; // May cause issues when multiple objects share the same pointer.
}
};
int main() {
Shallow obj1(10);
Shallow obj2 = obj1; // Shallow Copy
return 0;
}
Output:
yaml
obj1: 10
obj2: 10
After modification:
obj1: 20
obj2: 20
🔴 Problem: Both `obj1` and `obj2` share the same memory. When one is modified, the other also gets
affected.
cpp
#include <iostream>
using namespace std;
class Deep {
public:
int* ptr;
// Constructor
Deep(int val) {
ptr = new int(val);
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/5
// Destructor
~Deep() {
delete ptr;
}
};
int main() {
Deep obj1(10);
Deep obj2 = obj1; // Deep Copy
return 0;
}
Output:
yaml
obj1: 10
obj2: 10
After modification:
obj1: 10
obj2: 20
✅ Solution: Each object gets its own memory, preventing unintended modifications.
Conclusion
Use shallow copy when objects do not contain dynamically allocated memory.
Use deep copy when objects contain dynamically allocated memory to ensure each object has its
own copy.
For dynamically allocated objects, always implement deep copy to avoid dangling pointers and
memory leaks.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/5