Scope Resolution in C++ (1)
Scope Resolution in C++ (1)
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/13
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/13
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/13
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/13
// 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.
Definition:
A virtual function in C++ is a member function of a base class that can be overridden in a derived
class. It allows achieving runtime polymorphism, meaning the function that gets executed is
determined at runtime based on the actual type of the object, rather than the type of the
pointer/reference used to access it.
#include <iostream>
using namespace std;
class Base {
public:
void show() { // No virtual keyword
cout << "Base class show function" << endl;
}
};
int main() {
Base* ptr;
Derived obj;
ptr = &obj; // Base class pointer pointing to derived class object
Output:
pgsql
🔴 Problem: Even though `ptr` points to a `Derived` object, the base class function is called due to
static binding (compile-time binding).
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() { // Virtual function
cout << "Base class show function" << endl;
}
};
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/13
}
};
int main() {
Base* ptr;
Derived obj;
ptr = &obj;
Output:
pgsql
✅ Solution: The virtual function ensures that the derived class function is called at runtime, not
the base class function.
1. The compiler creates a Virtual Table (VTable), which stores pointers to virtual functions.
2. Each object of the class gets a hidden VPTR (Virtual Pointer) that points to the VTable.
3. When a virtual function is called using a base class pointer, the function is looked up in the VTable
at runtime, ensuring dynamic binding.
#include <iostream>
using namespace std;
class Base {
public:
Base() { cout << "Base Constructor\n"; }
~Base() { cout << "Base Destructor\n"; } // Non-virtual destructor
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/13
};
int main() {
Base* ptr = new Derived();
delete ptr; // Memory leak - Derived class destructor not called
return 0;
}
Output:
nginx
Base Constructor
Derived Constructor
Base Destructor
class Base {
public:
Base() { cout << "Base Constructor\n"; }
virtual ~Base() { cout << "Base Destructor\n"; } // Virtual destructor
};
int main() {
Base* ptr = new Derived();
delete ptr; // Proper cleanup
return 0;
}
Output:
nginx
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/13
cpp
class Base {
public:
virtual void show() = 0; // Pure virtual function (No definition)
};
int main() {
// Base obj; // ❌ ERROR: Cannot instantiate abstract class
Derived obj;
obj.show(); //
return 0;
✅ Works fine
}
✅ A class with at least one pure virtual function is called an abstract class, meaning it cannot be
instantiated directly.
7. Key Takeaways
Virtual functions enable dynamic binding and runtime polymorphism.
They allow function overriding to work correctly through base class pointers.
Always use a virtual destructor in polymorphic classes to prevent memory leaks.
Pure virtual functions make a class abstract, forcing derived classes to implement them.
A member function should be declared `const` when it does not modify any data members of the
class. This helps ensure read-only operations and enables calling the function on `const` objects.
Syntax:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/13
cpp
Example:
cpp
#include <iostream>
using namespace std;
class Demo {
private:
int value;
public:
Demo(int v) : value(v) {}
int main() {
✅ ❌
const Demo obj(10); // Creating a constant object
obj.show(); // Allowed (because `show()` is const)
// obj.setValue(20); ERROR (Cannot modify a const object)
return 0;
}
Output:
makefile
Value: 10
pgsql
Example:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/13
cpp
class Demo {
private:
const int value; // Constant member variable
public:
Demo(int v) : value(v) {} // Must be initialized in initializer list
int main() {
Demo obj(100);
}
obj.show();
// obj.value = 200; ❌ ERROR (Cannot modify const member)
✅ Reason: `value` is `const`, so it must be initialized in the constructor and cannot be changed.
Example:
cpp
void display(const string& str) { // `str` cannot be modified inside the function
cout << str << endl;
}
int main() {
string text = "Hello, World!";
}
display(text);
// text[0] = 'h'; // ✅
Allowed (text is non-const outside function)
✅ Reason: is passed by reference (`&`) to avoid unnecessary copying, but it cannot be modified
`str`
inside `display()`.
4. `const` in Pointers
Different Pointer Const Qualifiers:
cpp
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/13
Example in Classes:
cpp
class Demo {
private:
int* const ptr; // Constant pointer
public:
Demo(int val) : ptr(new int(val)) {}
5. `const` Objects
Purpose:
Example:
cpp
class Demo {
public:
void show() const { cout << "Const function" << endl; }
void modify() { cout << "Non-const function" << endl; }
};
int main() {
❌✅ERROR
const Demo obj;
obj.show(); // Allowed
// obj.modify(); (Cannot call non-const function)
}
✅ Reason: `const` objects can only call `const` functions to prevent modifications.
Key Takeaways
Feature Purpose Usage
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/13
Feature Purpose Usage
Ensures only `const` functions can be
`const` objects `const ClassName obj;`
called
🔹 Use wherever possible to improve code safety and prevent unintended modifications!
🚀
`const`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/13