WikiGalaxy

Personalize

Basic C++ Syntax

Variables and Data Types:

C++ supports several data types, including int, char, float, and double. Variables must be declared before they are used.

Functions:

Functions in C++ are blocks of code that perform a specific task. They must be declared and defined before they are called.

Control Structures:

C++ provides various control structures like if, else, switch, for, while, and do-while to control the flow of execution.

Operators:

Operators in C++ include arithmetic, relational, logical, bitwise, assignment, and other operators for performing operations on variables and values.

Classes and Objects:

C++ is an object-oriented language, allowing the creation of classes and objects to encapsulate data and functions.


#include <iostream>
using namespace std;

class Car {
  public:
    string brand;
    string model;
    int year;
    Car(string x, string y, int z) {
      brand = x;
      model = y;
      year = z;
    }
};

int main() {
  Car carObj1("BMW", "X5", 1999);
  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year;
  return 0;
}
    

Namespaces:

Namespaces are used to organize code into logical groups and to prevent name collisions in larger projects.

Pointers and References:

Pointers store memory addresses, while references are an alias for another variable. They are crucial for dynamic memory management.

Templates:

Templates allow functions and classes to operate with generic types, enabling code reuse and flexibility.

Exception Handling:

C++ provides try, catch, and throw keywords for handling exceptions and ensuring robust error management.

Standard Template Library (STL):

STL is a powerful library in C++ that provides generic classes and functions, including algorithms, iterators, and containers.

Console Output:

BMW X5 1999

Control Structures in C++

If-Else Statement:

The if-else statement allows conditional execution of code blocks based on boolean expressions.

Switch Case:

The switch statement is used to execute one block of code among many options based on the value of a variable.

For Loop:

The for loop is used to execute a block of code a specific number of times, providing initialization, condition, and increment expressions.

While Loop:

The while loop executes a block of code as long as the given condition is true.

Do-While Loop:

The do-while loop is similar to the while loop, but it guarantees at least one execution of the code block.


#include <iostream>
using namespace std;

int main() {
  int i = 0;
  while (i < 5) {
    cout << i << "\\n";
    i++;
  }
  return 0;
}
    

Break and Continue:

The break statement exits the current loop, while the continue statement skips the rest of the loop's current iteration.

Nested Loops:

Nested loops are loops within loops, allowing complex iteration patterns.

Console Output:

0\n1\n2\n3\n4

Functions in C++

Function Declaration and Definition:

Functions must be declared before they are used, and defined to specify the code they execute.

Return Type:

Every function has a return type that specifies what type of value it returns, or void if it doesn't return a value.

Parameters and Arguments:

Functions can have parameters to accept inputs, which are provided as arguments when the function is called.

Function Overloading:

C++ allows multiple functions with the same name but different parameters, known as function overloading.

Inline Functions:

Inline functions are expanded at the point of invocation, potentially improving performance by avoiding function call overhead.


#include <iostream>
using namespace std;

int add(int a, int b) {
  return a + b;
}

int main() {
  cout << add(5, 3);
  return 0;
}
    

Recursive Functions:

Recursive functions call themselves to solve smaller instances of the same problem, often used in algorithms like factorial and Fibonacci.

Console Output:

8

Object-Oriented Programming in C++

Classes and Objects:

Classes are blueprints for creating objects, encapsulating data and functions that operate on the data.

Constructors and Destructors:

Constructors initialize objects, while destructors clean up resources when objects are destroyed.

Inheritance:

Inheritance allows creating new classes based on existing ones, promoting code reuse and hierarchy.

Polymorphism:

Polymorphism allows functions to be used in multiple forms, achieved through function overloading and virtual functions.

Encapsulation:

Encapsulation restricts access to certain components of an object, using access specifiers like private, protected, and public.


#include <iostream>
using namespace std;

class Animal {
  public:
    void animalSound() {
      cout << "The animal makes a sound \\n";
    }
};

class Dog : public Animal {
  public:
    void animalSound() {
      cout << "The dog barks \\n";
    }
};

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

Abstraction:

Abstraction focuses on hiding complex implementation details and showing only essential features of an object.

Console Output:

The dog barks

Pointers and Dynamic Memory in C++

Pointers:

Pointers are variables that store memory addresses, enabling dynamic memory management and efficient array handling.

Dynamic Memory Allocation:

C++ uses new and delete operators for dynamic memory allocation and deallocation, allowing flexible memory usage.

Pointer Arithmetic:

Pointer arithmetic involves operations like addition and subtraction on pointers, useful for traversing arrays.

Null Pointers:

A null pointer is a special pointer value that points to nothing, used for initialization and error checking.

Smart Pointers:

Smart pointers, available in C++11, automatically manage memory and prevent memory leaks by using RAII principles.


#include <iostream>
using namespace std;

int main() {
  int* ptr;
  ptr = new int;
  *ptr = 10;
  cout << *ptr;
  delete ptr;
  return 0;
}
    

References vs Pointers:

References are an alias for another variable, providing safer and more intuitive syntax than pointers.

Console Output:

10

Templates in C++

Function Templates:

Function templates allow functions to operate with generic types, enabling code reuse and flexibility.

Class Templates:

Class templates enable the creation of classes that can work with any data type, enhancing code modularity and reusability.

Template Specialization:

Template specialization allows defining specific implementations for certain data types, optimizing performance and behavior.

Non-type Template Parameters:

Non-type template parameters allow templates to accept constant values as parameters, providing additional flexibility.

Variadic Templates:

Variadic templates, introduced in C++11, allow templates to accept an arbitrary number of arguments, simplifying code for complex operations.


#include <iostream>
using namespace std;

template <typename T>
T add(T a, T b) {
  return a + b;
}

int main() {
  cout << add(5, 3) << "\\n";
  cout << add(2.5, 3.7) << "\\n";
  return 0;
}
    

Template Metaprogramming:

Template metaprogramming uses templates to perform computations at compile time, optimizing runtime performance.

Console Output:

8\n6.2

Exception Handling in C++

Try and Catch Blocks:

The try block contains code that may throw an exception, while catch blocks handle specific exceptions.

Throwing Exceptions:

Exceptions can be thrown using the throw keyword, signaling that an error has occurred.

Standard Exceptions:

C++ provides a hierarchy of standard exception classes, including std::exception, std::runtime_error, and std::logic_error.

Custom Exceptions:

Developers can create custom exception classes to handle specific error conditions in their applications.

Exception Specifications:

Although deprecated in C++11, exception specifications were used to declare which exceptions a function might throw.


#include <iostream>
using namespace std;

int main() {
  try {
    int age = 15;
    if (age < 18) {
      throw age;
    }
  } catch (int e) {
    cout << "Access denied - You must be at least 18 years old. Age: " << e << "\\n";
  }
  return 0;
}
    

Stack Unwinding:

Stack unwinding is the process of cleaning up the stack when an exception is thrown, ensuring proper resource management.

Console Output:

Access denied - You must be at least 18 years old. Age: 15

The Standard Template Library (STL) in C++

Containers:

STL provides a variety of containers like vector, list, deque, set, map, and more, each serving different storage needs.

Iterators:

Iterators provide a way to access elements in a container sequentially without exposing the underlying representation.

Algorithms:

STL algorithms are a collection of functions for operations like searching, sorting, and manipulating data in containers.

Function Objects:

Function objects, or functors, are objects that can be used as though they are functions or function pointers.

Allocators:

Allocators handle memory allocation and deallocation for containers, providing flexibility in memory management.


#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> numbers = {1, 2, 3, 4, 5};
  for (int n : numbers) {
    cout << n << " ";
  }
  return 0;
}
    

Adapters:

Container adapters like stack, queue, and priority_queue provide restricted interfaces for specific use cases.

Console Output:

1 2 3 4 5

Preprocessor Directives in C++

Macros:

Macros are preprocessor directives that define code snippets, allowing code reuse and conditional compilation.

Include Directives:

Include directives insert the contents of a file into the program, commonly used to include header files.

Conditional Compilation:

Conditional compilation directives like #ifdef, #ifndef, #if, and #endif control which parts of the code are compiled.

Pragma Directives:

Pragma directives provide additional information to the compiler, often used for optimization and compatibility.

Error Directives:

Error directives generate compilation errors intentionally, useful for detecting unsupported configurations.


#include <iostream>
#define PI 3.14159
using namespace std;

int main() {
  cout << "Value of PI: " << PI;
  return 0;
}
    

Line Directives:

Line directives change the line number and filename reported by the compiler, useful for debugging and error reporting.

Console Output:

Value of PI: 3.14159

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025