Unit IV: Pointers and Polymorphism in C++
4.1 Concept of Pointer
A pointer is a variable that stores the address of another variable.
Pointers provide a way to access and manipulate memory locations directly.
- Pointer Declaration: int *ptr;
Here, 'ptr' is a pointer to an integer.
- Pointer Operator: The '*' operator is used to access the value at the address the pointer points to.
- Address Operator: The '&' operator is used to get the address of a variable.
- Pointer Arithmetic:
- Increment/Decrement: ptr++ or ptr-- moves the pointer to the next/previous memory location.
- Addition/Subtraction: ptr + n or ptr - n adds/subtracts n units from the pointer.
Example:
int a = 10;
int *ptr = &a; // ptr holds the address of a
std::cout << *ptr; // Outputs 10
4.2 Pointer to Object
Pointers can also point to objects. This allows dynamic memory allocation and the use of 'this' and
derived class pointers.
- 'this' Pointer:
- It refers to the current object of a class.
- Syntax: return *this;
- Pointer to Derived Class:
- A base class pointer can point to a derived class object.
Example:
class Base {};
class Derived : public Base {};
Base *bptr;
Derived d;
bptr = &d; // Base class pointer pointing to derived class object
4.3 Introduction to Polymorphism
Polymorphism means "many forms." It allows a single function or operator to behave differently
based on the input.
Types:
1. Compile-Time Polymorphism:
- Achieved using function overloading and operator overloading.
2. Run-Time Polymorphism:
- Achieved using virtual functions and inheritance.
4.4 Compile-Time Polymorphism
- Function Overloading:
- Functions with the same name but different parameters.
- Constructor Overloading:
- Multiple constructors with the same name but different parameters.
- Operator Overloading:
- Customizing the behavior of operators.
Rules for Operator Overloading:
1. Only existing operators can be overloaded.
2. At least one operand must be a user-defined type.
3. Cannot change operator precedence.
Example:
class Complex {
int real, imag;
public:
Complex operator+(Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
};
4.5 Run-Time Polymorphism
Run-time polymorphism is achieved using virtual functions and inheritance.
- Virtual Function:
- Declared using 'virtual' keyword in base class.
Rules:
1. Virtual functions must be defined in the base class.
2. Derived class must override the base class function.
- Pure Virtual Function:
- Declared using '= 0' syntax.
- Example: virtual void display() = 0;
Example:
class Base {
public:
virtual void show() {
std::cout << "Base class";
};
class Derived : public Base {
public:
void show() override {
std::cout << "Derived class";
}
};