C++ Derived Data Types
Derived data types in C++ are built from the fundamental (or basic) data types. They enable the creation of more complex data structures that can model real-world entities more effectively. Derived data types in C++ include arrays, functions, pointers, references, and user-defined types such as structures and classes. Here’s a detailed explanation of each derived data type:
1. Arrays
An array is a collection of elements of the same data type stored in contiguous memory locations. Arrays provide a way to store multiple values in a single variable, making it easier to manage related data.
Declaration:
int numbers[5]; // Array of 5 integers
Initialization:
int numbers[5] = {1, 2, 3, 4, 5}; // Initializing an array
Accessing Elements:
int firstNumber = numbers[0]; // Access the first element
2. Functions
Functions are blocks of code designed to perform a specific task. They can take inputs (parameters), perform operations, and return a value.
Function Declaration:
int add(int a, int b); // Declaration of a function
Function Definition:
int add(int a, int b) { return a + b; // Returns the sum of a and b }
Function Call:
int result = add(5, 10); // Calls the add function
3. Pointers
Pointers are variables that store the memory address of another variable. They are powerful tools in C++ that allow for dynamic memory management and efficient handling of arrays and structures.
Declaration:
int* ptr; // Pointer to an integer
Initialization:
int value = 10; ptr = &value; // Assigning the address of value to ptr
Dereferencing:
int dereferencedValue = *ptr; // Accessing the value at the address stored in ptr
4. References
References are another way to access variables in C++. A reference is an alias for an existing variable, providing a means to refer to it without copying the value.
Declaration:
int original = 20; int& ref = original; // ref is a reference to original
Usage:
ref = 30; // Changes the value of original to 30
5. User-Defined Data Types
C++ allows the creation of user-defined data types to model complex data structures.
a. Structures
Structures (struct
) group different data types under a single name.
Declaration:
struct Person { std::string name; int age; };
Usage:
Person person1; person1.name = "Alice"; person1.age = 30;
b. Classes
Classes are a fundamental part of C++'s object-oriented programming capabilities. They encapsulate data and functions into a single unit.
Declaration:
class Car { public: std::string brand; void honk() { std::cout << "Beep!" << std::endl; } };
Usage:
Car myCar; myCar.brand = "Toyota"; myCar.honk(); // Calls the honk method
6. Unions
Unions allow you to store different data types in the same memory location, but only one at a time. This can be useful for memory optimization.
Declaration:
union Data { int intValue; float floatValue; char charValue; };
Usage:
Data data; data.intValue = 5; // Using the union to store an int