C++ Basic to Advanced Core Concepts Study Guide

Introduction to C++ Programming

  • Course Overview:

    • Instructor: Love Babbar (Former Software Engineer at Amazon for 2.5 years and Microsoft for nearly a year).

    • Content: Covers C++ from basic to advanced levels across 20 chapters.

    • Structure: Includes over 100 solved questions, practice problems, homework, and source code access.

  • What is a Programming Language?

    • It is a language used by programmers/developers to communicate with machines (computers/devices).

    • Computers only understand Binary Language (zeros and ones).

    • A programming language allows humans to write instructions in a readable format, which is then converted into machine-understandable bits via a process called Compilation.

  • What is C++?

    • A high-performance programming language known for efficiency and speed.

    • Common use cases include:

      • Game Development.

      • Real-time systems.

      • System-level development.

      • Back-end creation.

      • Memory management and low-level resource access.

    • Major companies like Adobe use C++ extensively in their codebases.

  • Compilation Process:

    • Source Code: The code written by the programmer (e.g., in C++).

    • Compiler: A tool that converts source code into machine-understandable format.

    • Executable File: The resulting file (e.g., .exe on Windows) which, when run, executes the program.

    • Phases (Brief Overview): Pre-processing, Compilation, Assembly, and Linking.

Environment Setup (VS Code)

  • For macOS:

    • Download Visual Studio Code (VS Code).

    • Install the "C/C++ Extension Pack" and a compiler extension (like "C/C++ Compile Run").

    • Create a folder and a file with a .cpp extension (e.g., main.cpp).

  • For Windows:

    • Step 1: Install Compiler: Download MinGW (GCC Compiler Collection).

    • Step 2: Configure Environment Variables:

      • Copy the bin path from the MinGW installation directory (usually C:\MinGW\bin).

      • Search for "Environment Variables" in Windows settings.

      • Under "Path", add the copied bin path.

      • Verify installation in Command Prompt using gcc --version.

    • Step 3: VS Code: Download and install VS Code, install C/C++ extensions, and run code using the execution button (triangle icon).

Writing Your First Program: "Namaste Duniya"

  • Code Structure: ```cpp

    include

    using namespace std;

    int main() { cout << "Namaste Duniya" << endl; return 0; }     ```

  • Anatomy of the Program:

    • #include <iostream>: A Pre-processor Directive that includes the Input-Output Stream header file. It enables input/output functionalities.

    • using namespace std;: Specifies that the program uses the Standard (std) namespace, which contains definitions for cout and cin.

    • int main(): The starting point of every C++ program. Execution begins here.

    • { } (Braces): Define the scope of the function.

    • cout: An identifier/keyword for outputting data to the console.

    • <<: The Insertion Operator.

    • "Namaste Duniya": A String (sequence of characters in double quotes).

    • endl: A keyword for a new line (similar to hitting 'Enter').

    • ;: A semicolon marks the termination of a statement.

    • return 0;: Signals successful execution of the program to the Operating System. Non-zero returns (like 1, -1) indicate unsuccessful execution.

Data Types and Variables

  • Variables:

    • Named storage locations in memory.

    • Syntax: DataType VariableName = Value; (e.g., int age = 25;).

    • Declaration: int marks; (Allocates memory with a random garbage value).

    • Definition: int marks = 90; (Allocates memory and assigns a value).

    • Manipulation/Updation: marks = 100; (Changes the existing value).

  • Primitive Data Types:

    • int: Integers (usually 44 bytes / 3232 bits).

    • char: Characters in single quotes (e.g., 'a', 11 byte).

    • float: Floating-point numbers (decimal, 44 bytes).

    • double: Large floating-point numbers (88 bytes).

    • bool: Boolean values (true/1 or false/0, 11 byte).

      • Note: Even though a bool needs only 11 bit, it takes 11 byte because it is the smallest addressable space in memory.

  • Size and Range:

    • Use the sizeof() operator to find the memory size of a variable or type.

    • Signed vs. Unsigned:

      • Signed (Pos/Neg): Range is from 2(n1)-2^{(n-1)} to 2(n1)12^{(n-1)} - 1.

      • Unsigned (Pos only): Range is from 00 to 2n12^n - 1.

User Input

  • cin: A keyword in the std namespace used to take input from the terminal.

  • Syntax: cin >> variableName; (Uses the Extraction Operator >>).

  • Behavior: The program pauses and waits for user input. Once data is entered and 'Enter' is pressed, it is stored in the variable.

  • Note: To input a bool, use 00 for false and 11 for true; the literal strings "true" and "false" are not accepted by default via cin.

Control Flow: Decision Making

  • If Statement: Executes code only if a condition is true.

  • If-Else: Adds a fallback block if the condition is false.

  • If-Else-If: Chains multiple conditions.

  • Nested If: An if-statement inside another if-statement.

  • Switch Case:

    • Used for multi-way branching based on an expression (int or char).

    • Requires a break; statement after each case to prevent Fall-through (executing subsequent cases accidentally).

    • default: case is optional and runs if no match is found.

  • Ternary Operator: A shorthand for if-else.

    • Syntax: Condition ? ExpressionIfTrue : ExpressionIfFalse; (e.g., (age > 18) ? cout << "Can Vote" : cout << "Cannot Vote";).

Lops (Repetitive Tasks)

  • For Loop: Used when the number of iterations is known.

    • Syntax: for(initialization; condition; updation) { logic }.

  • While Loop: Used when the number of iterations is not strictly known; continues until the condition becomes false.

  • Do-While Loop: Similar to while, but the logic runs at least once because the condition is checked after the first execution.

  • Key Keywords:

    • break;: Exits the loop entirely.

    • continue;: Skips the current iteration and moves to the next.

  • Nested Loops: A loop inside another loop (e.g., used for 2D arrays or patterns).

Pointing and Dynamic Memory

  • Pointers:

    • A variable that stores the memory address of another variable.

    • & (Address-of Operator): Gets the address of a variable.

    • * (De-reference Operator): Accesses the value stored at the address a pointer is holding.

    • Example: cpp int a = 5; int* ptr = &a; // ptr stores address of a cout << *ptr; // Output: 5 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Memory Types:

    • Stack Memory: Fixed/static allocation. Managed automatically by the system.

    • Heep Memory: Dynamic allocation. Managed manually by the programmer using new and delete.

  • Dynamic Allocation:

    • int* ptr = new int; // Allocates an integer on the heap.

    • delete ptr; // Frees the memory (Prevents Memory Leaks).

    • int* arr = new int[size]; // Dynamic Array.

    • delete[] arr; // Dynamic Array De-allocation.

Arrays

  • Introduction:

    • Stores multiple items of the same type in contiguous memory locations.

    • Accesses elements using zero-based indexing (Indices from 00 to n1n-1).

  • 2D Arrays: Matrices with Rows and Columns.

    • Syntax: int arr[rows][cols];.

    • When passing 2D arrays to functions, the column size must be specified in the parameters.

  • Passing Arrays to Functions: Arrays are always passed by reference (the base address is passed, not the whole array copy).

Character Arrays and Strings

  • Char Arrays:

    • Require a Null Character ('\0') at the end to signify termination (ASCII value 00).

    • cout prints char arrays until the null character is reached.

  • Strings:

    • Part of the C++ Standard Library (std::string).

    • Dynamic in size and safer than char arrays.

    • Functions:

      • .length(): Returns length.

      • .append(): Concatenates.

      • .substr(pos, len): Extracts a substring.

      • .find(): Finds a pattern (returns string::npos if not found).

  • ASCII Values: Characters are internally stored as integers (e.g., 'A' = 6565, 'a' = 9797).

Reference Variables and Parameter Passing

  • Reference Variable: Giving another name to an existing variable.

    • int& temp = a; (Both temp and a refer to the same memory block).

  • Pass by Value: A copy of the variable is passed to the function. Changes inside the function do not affect the original variable.

  • Pass by Reference: The logic operates on the original memory block. Changes inside the function persist after the function ends.

Classes and Objects (Introduction)

  • Class: A blueprint or user-defined data type (e.g., Class Student).

  • Object: A real entity created based on the blueprint (e.g., Student s1;).

  • Data Members: Properties/attributes (e.g., int age;).

  • Member Functions: Behaviors/actions (e.g., void study();).

  • Access Modifiers: public members can be accessed outside the class.

  • Constructors: Special functions called automatically during object creation to initialize data members.

    • Default Constructor: No parameters.

    • Parameterized Constructor: Takes input to set properties.

  • this Keyword: A pointer that points to the current object in use.

  • Initializer List: A shorthand syntax for initializing data members in a constructor.

  • Destructor: Special function (~ClassName()) called when an object is destroyed, used mainly to free dynamic memory.