Agenda
- Constant
- Reference
- Static (Data Member & Member Functions)
- Dynamic Memory Allocation
- Simple and Dynamic Arrays (1D)
1. Constant (const
Keyword)
Definition:
const
is a type qualifier that makes a variable read-only.
- In C++, initializing a constant variable is mandatory.
const int num2; // ❌ Not OK: Must be initialized
const int num3 = 10; // ✅ OK: Initialized properly
1.1 Constant Data Members
- If a data member should not be modified inside any member function (including constructors), declare it
const
.
- A constant data member must be initialized using the constructor's member initializer list.
Example:
class Test {
private:
const int num1; // Constant data member
public:
Test() : num1(10) { } // ✅ Must be initialized in initializer list
};
1.2 Constant Member Functions
- A global function cannot be constant, but a member function can be constant.