0% found this document useful (0 votes)
16 views32 pages

Adv-Keywords With Sample Case Use

C keys as words
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views32 pages

Adv-Keywords With Sample Case Use

C keys as words
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

1.

asm

Using inline assembly to perform low-level operations:

============================================
#include <iostream>

int main() {
int result;
asm ("movl $5, %0" : "=r"(result)); // Inline assembly to move 5 into
result
std::cout << "Result from assembly: " << result << std::endl;
return 0;
}

The asm keyword allows embedding assembly code within C++ programs for low-level
hardware manipulation.

2. auto

Using auto for type inference with a lambda function:

============================================
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};

// Using lambda with auto


std::for_each(numbers.begin(), numbers.end(), [](auto n) {
std::cout << n * n << " "; // Squares each number
});

std::cout << std::endl;


return 0;
}

auto allows the compiler to deduce the type of variables, improving code readability and
maintainability.

3. volatile

Using volatile to prevent optimization on a shared variable in multithreading:

============================================
#include <iostream>
#include <thread>
#include <chrono>

volatile bool flag = false;

void setFlag() {
std::this_thread::sleep_for(std::chrono::seconds(1));
flag = true; // Set flag after 1 second
}

int main() {
std::thread t(setFlag);
while (!flag) {
// Busy wait
}
std::cout << "Flag was set!" << std::endl;
t.join();
return 0;
}

volatile informs the compiler that the variable may change unexpectedly, thus preventing it
from optimizing away checks on it.

4. while

Using while for reading input until a sentinel value is encountered:

============================================
#include <iostream>

int main() {
int number;
std::cout << "Enter numbers (0 to quit): ";

while (std::cin >> number && number != 0) {


std::cout << "You entered: " << number << std::endl;
}

return 0;
}

The while loop continues to execute as long as the condition is true, making it useful for
processing input until a specific condition is met.

5. bool

Using bool in a complex conditional statement:

============================================
#include <iostream>
int main() {
bool isValid = true;
bool hasPermission = false;

if (isValid && !hasPermission) {


std::cout << "Access denied." << std::endl;
} else {
std::cout << "Access granted." << std::endl;
}

return 0;
}

bool is a fundamental type used to represent truth values, enabling logical operations and
conditions.

6. break

Using break to exit a loop based on user input:

============================================
#include <iostream>

int main() {
for (int i = 0; i < 10; ++i) {
std::cout << "Iteration " << i << std::endl;
if (i == 5) {
break; // Exit loop when i is 5
}
}
return 0;
}

break terminates the nearest enclosing loop or switch statement, allowing for controlled
exits.

7. case

Using case in a switch statement for handling multiple options:

============================================
#include <iostream>

int main() {
int day = 3;

switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
default:
std::cout << "Invalid day" << std::endl;
break;
}

return 0;
}

case defines the specific values that a switch variable can take, facilitating cleaner multi-
branch decision-making.

8. catch

Using catch to handle exceptions in a try-catch block:

============================================
#include <iostream>
#include <stdexcept>

void mightGoWrong() {
throw std::runtime_error("Something went wrong!");
}

int main() {
try {
mightGoWrong();
} catch (const std::runtime_error& e) {
std::cout << "Caught an exception: " << e.what() << std::endl;
}
return 0;
}

catch specifies how to respond to exceptions of specific types, allowing for controlled error
handling.

9. char

Using char with a character array for string manipulation:

============================================
#include <iostream>

int main() {
char name[] = "John Doe";
for (char c : name) {
if (c == ' ') {
std::cout << "Space found!" << std::endl;
} else {
std::cout << c << std::endl; // Print each character
}
}
return 0;
}

char is used to represent single characters or create character arrays, often utilized in string
handling.

10. class

Defining a class with encapsulation and member functions:

============================================
#include <iostream>

class Rectangle {
public:
Rectangle(double w, double h) : width(w), height(h) {}

double area() {
return width * height;
}

private:
double width;
double height;
};

int main() {
Rectangle rect(5.0, 3.0);
std::cout << "Area: " << rect.area() << std::endl; // Output: 15
return 0;
}

class is a fundamental building block of C++ object-oriented programming, allowing for


encapsulation and abstraction.

11. const

Using const to define a read-only variable:

============================================
#include <iostream>
int main() {
const int MAX_ITEMS = 100; // Constant value
std::cout << "Max items: " << MAX_ITEMS << std::endl;

// MAX_ITEMS = 200; // Uncommenting this line will cause a compilation


error

return 0;
}

const indicates that a variable’s value cannot be changed after initialization, promoting
safety and clarity.

12. const_cast

Using const_cast to remove constness from a variable:

============================================
#include <iostream>

void printValue(const int* ptr) {


// const_cast to modify const int
int* mutablePtr = const_cast<int*>(ptr);
*mutablePtr = 100; // Changing the value
}

int main() {
int x = 10;
printValue(&x);
std::cout << "Modified value: " << x << std::endl; // Output: 100
return 0;
}

const_cast allows casting away the const qualifier, enabling modifications of originally
constant variables.

13. continue

Using continue to skip an iteration in a loop:

============================================
#include <iostream>

int main() {
for (int i = 0; i < 10; ++i) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
std::cout << i << " "; // Output: 1 3 5 7 9
}
std::cout << std::endl;
return 0;
}

continue skips the rest of the loop iteration and proceeds to the next one, allowing for
selective processing of loop elements.

14. default

Using default in a switch statement:

============================================
#include <iostream>

int main() {
int option = 4;

switch (option) {
case 1:
std::cout << "Option 1" << std::endl;
break;
case 2:
std::cout << "Option 2" << std::endl;
break;
default:
std::cout << "Invalid option" << std::endl; // Executes if no
case matches
break;
}
return 0;
}

default specifies the action to take when no case matches in a switch statement, serving as a
fallback option.

15. delete

Using delete to free dynamically allocated memory:

============================================
#include <iostream>

int main() {
int* ptr = new int(5); // Dynamically allocate an integer
std::cout << "Value: " << *ptr << std::endl;
delete ptr; // Free memory
return 0;
}
delete releases memory allocated with new, preventing memory leaks in dynamic memory
management.

16. do

Using do-while for a post-test loop:

============================================
#include <iostream>

int main() {
int number;
do {
std::cout << "Enter a positive number (negative to quit): ";
std::cin >> number;
} while (number >= 0);

std::cout << "You entered a negative number." << std::endl;


return 0;
}

The do keyword initiates a loop that guarantees at least one execution, useful for user input
validation.

17. double

Using double for precise floating-point arithmetic:

============================================
#include <iostream>

int main() {
double length = 5.5;
double width = 2.3;
double area = length * width;

std::cout << "Area of rectangle: " << area << std::endl; // Output:
12.65
return 0;
}

double provides greater precision than float, making it suitable for calculations requiring
significant decimal places.

18. dynamic_cast
Using dynamic_cast for safe downcasting in polymorphism:

============================================
#include <iostream>
#include <typeinfo>

class Base {
public:
virtual ~Base() {}
};

class Derived : public Base {};

int main() {
Base* basePtr = new Derived(); // Base pointer to Derived object
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr); // Safe
downcasting

if (derivedPtr) {
std::cout << "Successfully downcasted to Derived." << std::endl;
} else {
std::cout << "Downcasting failed." << std::endl;
}

delete basePtr;
return 0;
}

dynamic_cast performs a safe runtime check when downcasting, ensuring that the object is
of the correct type.

19. else

Using else for alternative conditions in if statements:

============================================
#include <iostream>

int main() {
int score = 75;

if (score >= 90) {


std::cout << "Grade: A" << std::endl;
} else if (score >= 80) {
std::cout << "Grade: B" << std::endl;
} else {
std::cout << "Grade: C" << std::endl; // Default case
}

return 0;
}
else provides a fallback option in conditional branching, ensuring that one of the paths is
taken.

20. enum

Defining an enum for a set of named constants:

============================================
#include <iostream>

enum class Color { Red, Green, Blue };

int main() {
Color favoriteColor = Color::Blue;

switch (favoriteColor) {
case Color::Red:
std::cout << "Favorite color is Red." << std::endl;
break;
case Color::Green:
std::cout << "Favorite color is Green." << std::endl;
break;
case Color::Blue:
std::cout << "Favorite color is Blue." << std::endl; // Output
break;
}

return 0;
}

enum defines a set of named constants, enhancing code readability and maintainability.

21. except

Note: except is not a standard C++ keyword; it may be from another language context. The
closest in C++ is try and catch. I will skip this one unless you need it in a specific context.

22. explicit

Using explicit to prevent implicit conversions in constructors:

============================================
#include <iostream>

class Fraction {
public:
explicit Fraction(int num) : numerator(num), denominator(1) {}
void display() const {
std::cout << numerator << "/" << denominator << std::endl;
}

private:
int numerator;
int denominator;
};

int main() {
Fraction frac(5); // Explicitly constructed
frac.display();

// Fraction anotherFrac = 10; // This would be an error without


explicit

return 0;
}

explicit prevents automatic type conversions, ensuring that constructors are called only
when intended.

23. extern

Using extern to declare a variable defined in another translation unit:

============================================
#include <iostream>

extern int sharedValue; // Declaration

int main() {
std::cout << "Shared value: " << sharedValue << std::endl; // Uses the
value from another file
return 0;
}

extern is used for variable declarations across multiple files, facilitating linkage in larger
programs.

24. false

Using false in a boolean context:

============================================
#include <iostream>

int main() {
bool flag = false;
if (!flag) {
std::cout << "Flag is false." << std::endl; // Output
}

return 0;
}

false represents a boolean false value, essential for conditional checks and logical
operations.

25. finally

Note: finally is not a standard C++ keyword. In C++, we typically use RAII principles for
cleanup. I’ll skip this one as well.

26. float

Using float for single-precision floating-point arithmetic:

============================================
#include <iostream>

int main() {
float radius = 2.5f;
float area = 3.14f * radius * radius;

std::cout << "Area of circle: " << area << std::endl; // Output: Area
of circle: 19.625
return 0;
}

float is used for single-precision floating-point calculations, suitable for applications where
memory is a concern.

27. for

Using for for iterating through an array:

============================================
#include <iostream>

int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < size; ++i) {
std::cout << "Element " << i << ": " << arr[i] << std::endl;
}

return 0;
}

The for loop provides a concise way to iterate over a range or a collection of elements.

28. friend

Using friend to allow a function to access private members of a class:

============================================
#include <iostream>

class Box {
public:
Box(int l, int w, int h) : length(l), width(w), height(h) {}

friend int calculateVolume(const Box& box); // Friend function


declaration

private:
int length, width, height;
};

int calculateVolume(const Box& box) {


return box.length * box.width * box.height; // Accessing private
members
}

int main() {
Box box(3, 4, 5);
std::cout << "Volume of the box: " << calculateVolume(box) <<
std::endl; // Output: 60
return 0;
}

friend allows specific functions or classes to access private or protected members,


promoting encapsulation while enabling flexibility.

29. goto

Using goto for non-linear control flow (not generally recommended):

============================================
#include <iostream>

int main() {
int count = 0;

start:
std::cout << "Count: " << count << std::endl;
count++;

if (count < 5) {
goto start; // Jump back to start
}

return 0;
}

While goto can create jumps in control flow, its use is often discouraged in favor of
structured programming constructs for better readability and maintainability.

30. if

Advanced conditional logic using if in a function that implements memoization to optimize


recursive calls.

============================================
#include <iostream>
#include <unordered_map>

std::unordered_map<int, int> fib_cache;

int fibonacci(int n) {
if (fib_cache.find(n) != fib_cache.end()) {
return fib_cache[n];
}
if (n <= 1) {
return n;
} else {
fib_cache[n] = fibonacci(n - 1) + fibonacci(n - 2);
return fib_cache[n];
}
}

int main() {
std::cout << "Fibonacci(10): " << fibonacci(10) << std::endl;
return 0;
}

Here, the if condition checks if the Fibonacci value for a given number has already been
calculated and stored, optimizing the function.

31. inline

Inlining is useful for small functions that are frequently called. Here's a case where it helps
with function templating in class definition:
============================================
template <typename T>
class MathOps {
public:
inline T multiply(T a, T b) {
return a * b;
}
};

int main() {
MathOps<int> math;
std::cout << math.multiply(5, 3) << std::endl; // Output: 15
return 0;
}

This reduces the overhead of frequent function calls in template classes, where speed is
critical.

32. int

Working with advanced data structures such as graphs:

============================================
#include <iostream>
#include <vector>

int main() {
int vertices = 5;
std::vector<std::vector<int>> graph(vertices,
std::vector<int>(vertices, 0));

// Adding edges to the graph


graph[0][1] = 1;
graph[1][2] = 1;
graph[2][3] = 1;

// Output adjacency matrix


for (int i = 0; i < vertices; ++i) {
for (int j = 0; j < vertices; ++j) {
std::cout << graph[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}

Here, int is used to define the number of vertices and edges in a graph.

33. long

Handling large values, such as factorial calculations:

============================================
#include <iostream>
long factorial(long n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}

int main() {
long number = 20; // Factorial of large number
std::cout << "Factorial of " << number << " is " << factorial(number)
<< std::endl;
return 0;
}

Here, long is needed to handle the large numbers produced by factorials.

34. mutable

A mutable member in a multi-threaded logging system:

============================================
#include <iostream>
#include <string>
#include <mutex>

class Logger {
mutable std::mutex mtx;
std::string log;

public:
void log_message(const std::string& message) const {
std::lock_guard<std::mutex> lock(mtx);
log += message + "\n";
}

void print_log() const {


std::cout << log << std::endl;
}
};

int main() {
Logger logger;
logger.log_message("Initializing system...");
logger.log_message("System started.");
logger.print_log();
return 0;
}

The mutable keyword allows the mutex to be modified even when log_message is called on
a const object.

35. namespace

Managing large projects with multiple libraries:

============================================
#include <iostream>
namespace Graphics {
void draw() {
std::cout << "Drawing from Graphics namespace" << std::endl;
}
}

namespace Physics {
void draw() {
std::cout << "Drawing from Physics namespace" << std::endl;
}
}

int main() {
Graphics::draw();
Physics::draw();
return 0;
}

Using namespace helps to avoid naming conflicts in larger projects where libraries might
define functions with similar names.

36. new

Allocating memory for complex data structures such as a dynamic tree:

============================================
#include <iostream>

struct Node {
int value;
Node* left;
Node* right;
Node(int v) : value(v), left(nullptr), right(nullptr) {}
};

int main() {
Node* root = new Node(10);
root->left = new Node(5);
root->right = new Node(15);

std::cout << "Root Value: " << root->value << std::endl;


std::cout << "Left Child: " << root->left->value << std::endl;
std::cout << "Right Child: " << root->right->value << std::endl;

delete root->left;
delete root->right;
delete root;
return 0;
}

In this example, new is used to dynamically allocate nodes of a binary tree.

37. operator

Overloading the [] operator for a custom array class:


============================================
#include <iostream>

class Array {
int* data;
int size;

public:
Array(int size) : size(size) {
data = new int[size];
}

int& operator[](int index) {


if (index >= size) {
std::cerr << "Array index out of bounds!" << std::endl;
exit(1);
}
return data[index];
}

~Array() {
delete[] data;
}
};

int main() {
Array arr(10);
arr[0] = 100;
std::cout << arr[0] << std::endl;
return 0;
}

Here, the [] operator is overloaded to allow direct access to the array elements.

38. private

Data encapsulation in a class using private access:

============================================
class BankAccount {
private:
double balance;

public:
BankAccount() : balance(0) {}

void deposit(double amount) {


if (amount > 0) balance += amount;
}

double getBalance() const {


return balance;
}
};

Private data members ensure that the balance cannot be directly accessed or modified from
outside the class.
39. protected

Inheriting classes with protected members:

============================================
#include <iostream>

class Animal {
protected:
std::string species;
public:
Animal(const std::string& spec) : species(spec) {}
};

class Dog : public Animal {


public:
Dog() : Animal("Dog") {}

void speak() {
std::cout << "I am a " << species << std::endl;
}
};

int main() {
Dog myDog;
myDog.speak();
return 0;
}

Here, the protected member species is accessible to the derived class Dog.

40. public

In a large inheritance hierarchy, public members can be accessed from outside:

============================================
#include <iostream>

class Base {
public:
void show() {
std::cout << "Base class" << std::endl;
}
};

class Derived : public Base {


public:
void show() {
std::cout << "Derived class" << std::endl;
}
};

int main() {
Derived obj;
obj.show(); // Outputs "Derived class"
obj.Base::show(); // Outputs "Base class"
return 0;
}

The derived class show() method is called, but the Base class method can also be accessed
due to public inheritance.

41. register

Though mostly ignored by modern compilers, register can still hint for small, frequently
used variables:

============================================
void addNumbers() {
register int sum = 0;
for (register int i = 0; i < 1000; ++i) {
sum += i;
}
std::cout << "Sum: " << sum << std::endl;
}

43. return

Using return in a function that handles large computations and returns early based on a
condition:

============================================
#include <iostream>

int expensiveComputation(int n) {
if (n < 0) {
return -1; // Return early for invalid input
}

int result = 0;
for (int i = 0; i < n; ++i) {
result += i * i; // Some complex computation
}
return result;
}

int main() {
std::cout << "Computation result: " << expensiveComputation(5) <<
std::endl;
return 0;
}

Here, the function uses return to handle invalid inputs early, making the code more efficient
and readable.

44. short
Handling short type with bit-level operations:

============================================
#include <iostream>

int main() {
short a = 0b10101010; // 170 in binary
short b = 0b11001100; // 204 in binary

short result = a & b; // Bitwise AND


std::cout << "Bitwise AND: " << result << std::endl; // Output: 136
return 0;
}

Here, short is used for bitwise operations, showcasing its use in memory-constrained
environments where smaller integer types are preferred.

45. signed

This keyword explicitly specifies that a variable can hold both positive and negative values:

============================================
#include <iostream>

int main() {
signed int a = -42;
signed int b = 1024;

std::cout << "a: " << a << ", b: " << b << std::endl;
return 0;
}

While int is signed by default, explicitly using signed can improve code clarity, particularly
when mixing with unsigned types.

46. sizeof

An advanced use of sizeof to calculate the size of dynamically allocated arrays or struct
padding:

============================================
#include <iostream>

struct MyStruct {
char a;
int b;
double c;
};
int main() {
MyStruct obj;
std::cout << "Size of MyStruct: " << sizeof(MyStruct) << " bytes" <<
std::endl;

int* arr = new int[10];


std::cout << "Size of dynamically allocated array: " << sizeof(arr) *
10 << " bytes" << std::endl;
delete[] arr;
return 0;
}

sizeof helps in understanding memory layout and calculating storage space for dynamic
memory allocations.

47. static

Using static for data persistence across function calls:

============================================
#include <iostream>

void counter() {
static int count = 0;
++count;
std::cout << "Count: " << count << std::endl;
}

int main() {
for (int i = 0; i < 5; ++i) {
counter();
}
return 0;
}

Here, static ensures that the count variable retains its value between function calls,
effectively making it a function-level "global."

48. static_cast

Safe casting in a class hierarchy, converting a base pointer to a derived pointer:

============================================
#include <iostream>

class Base {
public:
virtual void show() { std::cout << "Base class" << std::endl; }
};
class Derived : public Base {
public:
void show() override { std::cout << "Derived class" << std::endl; }
};

int main() {
Base* basePtr = new Derived();
Derived* derivedPtr = static_cast<Derived*>(basePtr);
derivedPtr->show(); // Outputs: Derived class
delete basePtr;
return 0;
}

static_cast is used here to convert a base class pointer to a derived class pointer, ensuring
type safety.

49. struct

Advanced use of struct in implementing a linked list:

============================================
#include <iostream>

struct Node {
int data;
Node* next;
};

void printList(Node* head) {


Node* temp = head;
while (temp != nullptr) {
std::cout << temp->data << " ";
temp = temp->next;
}
}

int main() {
Node* head = new Node{1, nullptr};
head->next = new Node{2, nullptr};
head->next->next = new Node{3, nullptr};

printList(head); // Output: 1 2 3
return 0;
}

struct is commonly used in data structures like linked lists due to its simplicity and default
public access.

50. switch
Advanced control flow with switch using enum types:

============================================
#include <iostream>

enum class Color { Red, Green, Blue };

void printColor(Color color) {


switch (color) {
case Color::Red:
std::cout << "Red" << std::endl;
break;
case Color::Green:
std::cout << "Green" << std::endl;
break;
case Color::Blue:
std::cout << "Blue" << std::endl;
break;
default:
std::cout << "Unknown color" << std::endl;
}
}

int main() {
printColor(Color::Green); // Output: Green
return 0;
}

Here, switch is used with scoped enums (enum class), ensuring type safety.

51. template

Template specialization for advanced generic programming:

============================================
#include <iostream>

template <typename T>


void print(T value) {
std::cout << "Generic: " << value << std::endl;
}

template <>
void print<int>(int value) {
std::cout << "Specialized for int: " << value << std::endl;
}

int main() {
print(42); // Specialized for int
print(3.14); // Generic
print("Hello"); // Generic
return 0;
}
template allows code to be reused for different types, with specialization enabling
customization for specific types.

52. this

Using this in an advanced way with method chaining:

============================================
#include <iostream>

class Chainable {
int value;

public:
Chainable() : value(0) {}

Chainable& add(int x) {
value += x;
return *this;
}

Chainable& subtract(int x) {
value -= x;
return *this;
}

void print() {
std::cout << "Value: " << value << std::endl;
}
};

int main() {
Chainable obj;
obj.add(10).subtract(3).add(5).print(); // Output: Value: 12
return 0;
}

this allows method chaining, where multiple methods can be called in a sequence on the
same object.

53. throw

Throwing and catching exceptions in error handling:

============================================
#include <iostream>

int divide(int a, int b) {


if (b == 0) {
throw std::runtime_error("Division by zero");
}
return a / b;
}

int main() {
try {
std::cout << divide(10, 2) << std::endl; // Outputs 5
std::cout << divide(10, 0) << std::endl; // Throws exception
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}

Here, throw is used to raise an exception when an error condition occurs (division by zero),
and try-catch blocks are used to handle it.

54. true

Advanced conditional checks with true in a multi-threaded loop:

============================================
#include <iostream>
#include <thread>
#include <atomic>

std::atomic<bool> flag(true);

void worker() {
while (flag) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "Working..." << std::endl;
}
}

int main() {
std::thread t(worker);

std::this_thread::sleep_for(std::chrono::seconds(1));
flag = false;

t.join();
return 0;
}

In this example, true is used with a flag to control a multi-threaded loop that terminates
when the flag is set to false.

55. try

Using try for exception handling with custom exceptions:


============================================
#include <iostream>
#include <stdexcept>

class MyException : public std::runtime_error {


public:
MyException(const std::string& message) : std::runtime_error(message)
{}
};

void riskyOperation(int num) {


if (num < 0) {
throw MyException("Negative number error");
}
std::cout << "Operation successful: " << num << std::endl;
}

int main() {
try {
riskyOperation(10); // Valid operation
riskyOperation(-5); // Will throw an exception
} catch (const MyException& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
}
return 0;
}

In this example, try is used to catch a custom exception when a risky operation fails.

56. type_info

Utilizing type_info to get runtime type information:

============================================
#include <iostream>
#include <typeinfo>

class Base {
public:
virtual ~Base() {}
};

class Derived : public Base {};

void printTypeInfo(Base* base) {


std::cout << "Type: " << typeid(*base).name() << std::endl; // RTTI
}

int main() {
Base* base = new Derived();
printTypeInfo(base); // Outputs the type of Derived
delete base;
return 0;
}
type_info provides information about the type of an object at runtime, especially useful in
polymorphic scenarios.

57. typedef

Creating aliases for complex types using typedef:

============================================
#include <iostream>
#include <vector>

typedef std::vector<std::pair<int, int>> PointList;

int main() {
PointList points = { {1, 2}, {3, 4}, {5, 6} };

for (const auto& point : points) {


std::cout << "Point: (" << point.first << ", " << point.second <<
")" << std::endl;
}
return 0;
}

Here, typedef is used to simplify the declaration of a complex type, making the code more
readable.

58. typeid

Using typeid to get the type of an object at runtime, demonstrating polymorphism:

============================================
#include <iostream>
#include <typeinfo>

class Base {
public:
virtual ~Base() {}
};

class Derived : public Base {};

int main() {
Base* obj = new Derived();
std::cout << "Type of obj: " << typeid(*obj).name() << std::endl; //
Outputs the type of Derived
delete obj;
return 0;
}
typeid is particularly useful for checking the actual type of an object when working with
polymorphism.

59. typename

Using typename in template programming to define dependent types:

============================================
#include <iostream>
#include <vector>

template <typename T>


class MyContainer {
public:
void add(const T& item) {
data.push_back(item);
}

typename std::vector<T>::iterator begin() {


return data.begin();
}

private:
std::vector<T> data;
};

int main() {
MyContainer<int> container;
container.add(10);
std::cout << "First element: " << *container.begin() << std::endl; //
Output: 10
return 0;
}

typename is used here to indicate that std::vector<T>::iterator is a type dependent on


the template parameter T.

60. union

Using union for memory-efficient data representation:

============================================
#include <iostream>

union Data {
int intValue;
float floatValue;
char charValue;
};
int main() {
Data data;
data.intValue = 42;
std::cout << "Integer: " << data.intValue << std::endl;

data.floatValue = 3.14; // Overwrites intValue


std::cout << "Float: " << data.floatValue << std::endl; // Only
floatValue is valid

data.charValue = 'A'; // Overwrites floatValue


std::cout << "Char: " << data.charValue << std::endl; // Only
charValue is valid

return 0;
}

union allows storing different data types in the same memory location, but only one member
can hold a value at a time.

61. unsigned

Using unsigned to ensure non-negative values, particularly in bit manipulation:

============================================
#include <iostream>

int main() {
unsigned int a = 5;
unsigned int b = 10;

unsigned int result = a + b; // No risk of negative result


std::cout << "Unsigned result: " << result << std::endl; // Output: 15

return 0;
}

unsigned types are useful when you know that negative values are not needed, thus
providing a larger range for positive values.

62. using

Utilizing using for type aliases and namespace declarations:

============================================
#include <iostream>
#include <vector>

using IntVector = std::vector<int>; // Type alias

int main() {
IntVector numbers = {1, 2, 3, 4, 5};
for (const auto& num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}

The using directive provides an alternative to typedef, making code cleaner and more
expressive.

63. virtual

Using virtual in a polymorphic class hierarchy to allow runtime method resolution:

============================================
#include <iostream>

class Base {
public:
virtual void show() {
std::cout << "Base class" << std::endl;
}
virtual ~Base() {}
};

class Derived : public Base {


public:
void show() override {
std::cout << "Derived class" << std::endl;
}
};

int main() {
Base* basePtr = new Derived();
basePtr->show(); // Outputs: Derived class
delete basePtr;
return 0;
}

The virtual keyword enables dynamic dispatch, allowing derived class methods to be called
through base class pointers.

64. void

Using void as a return type for functions that do not return a value:

============================================
#include <iostream>
void printMessage() {
std::cout << "This is a message." << std::endl;
}

int main() {
printMessage(); // Calls the function
return 0;
}

void indicates that the function does not return any value, which is common for functions
that perform actions but do not need to send data back

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy