C++ Derived Data Types
Derived data types in C++ are built from primitive data types. They allow programmers to create more complex data structures such as arrays, pointers, references, and functions.
1. Types of Derived Data Types
- Array - Collection of elements of the same type.
- Pointer - Stores the memory address of a variable.
- Reference - Alias for an existing variable.
- Function - Block of reusable code.
2. Arrays
An array is a collection of elements of the same data type stored in contiguous memory locations.
#include <iostream>
using namespace std;
int main() {
int numbers[3] = {10, 20, 30};
cout << "First Element: " << numbers[0] << endl;
cout << "Second Element: " << numbers[1] << endl;
cout << "Third Element: " << numbers[2] << endl;
return 0;
}
3. Pointers
A pointer is a variable that stores the memory address of another variable.
#include <iostream>
using namespace std;
int main() {
int value = 100;
int* ptr = &value;
cout << "Value: " << value << endl;
cout << "Address: " << ptr << endl;
cout << "Value using pointer: " << *ptr << endl;
return 0;
}
4. References
A reference is an alias for an existing variable. Once a reference is initialized, it cannot be changed to refer to another variable.
#include <iostream>
using namespace std;
int main() {
int x = 50;
int& ref = x;
cout << "Original Value: " << x << endl;
cout << "Reference Value: " << ref << endl;
ref = 80;
cout << "Updated Value: " << x << endl;
return 0;
}
5. Functions
A function is a block of code that performs a specific task and can be reused multiple times.
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(10, 20);
cout << "Sum: " << result;
return 0;
}
6. Complete Example Using Derived Data Types
#include <iostream>
using namespace std;
int multiply(int a, int b) {
return a * b;
}
int main() {
int arr[2] = {5, 10};
int x = 20;
int* ptr = &x;
int& ref = x;
cout << "Array First Element: " << arr[0] << endl;
cout << "Pointer Value: " << *ptr << endl;
cout << "Reference Value: " << ref << endl;
cout << "Multiplication Result: " << multiply(3, 4) << endl;
return 0;
}
Conclusion
Derived data types in C++ extend the capabilities of primitive data types. Arrays help store multiple values, pointers manage memory, references provide aliases, and functions enable reusable logic. Mastering these is essential before moving to advanced C++ concepts like classes and templates.
Codecrown