Blog

  • Ruby Methods

    A method in Ruby is a reusable block of code that performs a specific task and optionally returns a value. Methods help reduce repetition by letting you define logic once and call it multiple times.

    In Ruby, methods are defined using the def keyword and closed with end. Method names are typically written in lowercase (snake_case).


    Defining and Calling a Method

    A method must be defined before it can be called.

    Basic Syntax

    def method_name
      # statements
    end
    

    Example:

    def welcome
      puts "Hello! Welcome to Ruby Programming."
    end
    
    welcome
    

    Output:

    Hello! Welcome to Ruby Programming.
    

    Passing Parameters to Methods

    You can pass values into a method using parameters. Ruby also supports default parameter values, which are used if the caller does not provide an argument.

    Example with Default Values

    def display_info(name = "Ruby", level = "Beginner")
      puts "Language: #{name}"
      puts "Level: #{level}"
    end
    
    display_info "Python", "Intermediate"
    puts ""
    display_info
    

    Output:

    Language: Python
    Level: Intermediate
    
    Language: Ruby
    Level: Beginner
    

    Accepting a Variable Number of Arguments

    When the number of arguments is unknown, Ruby lets you collect them using the splat operator *.

    Example-

    def show_items(*items)
      puts "Number of items: #{items.length}"
      items.each_with_index do |item, index|
        puts "Item #{index + 1}: #{item}"
      end
    end
    
    show_items "Apple", "Banana", "Cherry"
    show_items "Orange"
    

    Returning Values from Methods

    Ruby automatically returns the value of the last evaluated expression. You only need return when you want to exit early or return multiple values explicitly.

    Eg:

    def calculate_sum
      num1 = 25
      num2 = 75
      num1 + num2
    end
    
    puts "The sum is: #{calculate_sum}"
    

    Method Visibility in Ruby

    Method visibility determines where methods can be called from. Ruby provides three access levels:

    • public (default): callable from anywhere
    • protected: callable within the class and its subclasses, often for comparisons between instances
    • private: callable only inside the class, and not with an explicit receiver (even self)

    Public Methods Example

    class Example
      def public_method1
        puts "public_method1 called!"
      end
    
      public
    
      def public_method2
        puts "public_method2 called!"
      end
    end
    
    obj = Example.new
    obj.public_method1
    obj.public_method2
    

    Protected Methods Example

    class Parent
      protected
    
      def protected_method
        puts "protected_method called!"
      end
    end
    
    class Child < Parent
      def call_protected
        protected_method
      end
    end
    
    Child.new.call_protected
    

    Private Methods Example

    class Example
      private
    
      def private_method
        puts "private_method called!"
      end
    
      public
    
      def public_method
        private_method
      end
    end
    
    Example.new.public_method
    

    Recursion in Ruby

    Recursion happens when a method calls itself to solve a problem in smaller steps. It can make certain solutions elegant, but Ruby recursion can cause stack overflow for very large inputs.


    Iterative vs Recursive Array Sum

    Iterative:

    def iterative_sum(numbers)
      sum = 0
      numbers.each { |n| sum += n }
      sum
    end
    
    puts iterative_sum([1, 2, 3, 4, 5])
    

    Recursive:

    def recursive_sum(numbers)
      return 0 if numbers.empty?
      numbers[0] + recursive_sum(numbers[1..])
    end
    
    puts recursive_sum([1, 2, 3, 4, 5])
    

    Recursive Factorial Example

    def factorial(n)
      return 1 if n <= 1
      n * factorial(n - 1)
    end
    
    puts factorial(5)
    

    Recursive Fibonacci Example

    def fibonacci(n)
      return n if n < 2
      fibonacci(n - 1) + fibonacci(n - 2)
    end
    
    puts fibonacci(5)
    

    Tip: recursive Fibonacci is slow for large values—use iteration or memoization in real projects.


    Ruby Hook Methods

    Hook methods are special methods triggered by events such as including a module, inheriting from a class, or calling undefined methods.

    Common hook methods include:

    • included
    • prepended
    • extended
    • inherited
    • method_missing

    included Hook

    module WelcomeMessage
      def self.included(target)
        puts "The #{target} has been greeted with a warm welcome!"
      end
    end
    
    class User
      include WelcomeMessage
    end
    

    prepended Hook

    module Language
      def self.prepended(target)
        puts "#{self} has been prepended to #{target}"
      end
    
      def description
        "The language used is Ruby."
      end
    end
    
    class Programming
      prepend Language
    end
    
    puts Programming.new.description
    

    extended Hook

    module Framework
      def self.extended(target)
        puts "#{self} was extended by #{target}"
      end
    
      def description
        "This framework is based on Ruby."
      end
    end
    
    class Software
      extend Framework
    end
    
    puts Software.description
    

    inherited Hook

    class Vehicle
      def self.inherited(subclass)
        puts "#{subclass} is a subclass of Vehicle"
      end
    end
    
    class Car < Vehicle
    end
    

    method_missing

    class Language
      def method_missing(method_name, *args)
        "#{method_name} is not defined for #{self}"
      end
    
      def known_method
        "This method is defined."
      end
    end
    
    obj = Language.new
    puts obj.known_method
    puts obj.unknown_method
    

    Ruby Range Class Methods and Examples

    A Range represents a sequence between two values.

    • .. includes the end value
    • ... excludes the end value

    Creating Ranges

    (1..6).to_a    # => [1, 2, 3, 4, 5, 6]
    (1...6).to_a   # => [1, 2, 3, 4, 5]
    

    Useful Range Methods

    range = (3..10)
    
    puts range.begin      # 3
    puts range.end        # 10
    puts range.first      # 3
    puts range.last       # 10
    puts range.include?(5)  # true
    puts range.include?(15) # false
    

    Iteration with each and step

    (1..5).each { |i| print "#{i} " }
    puts ""
    
    (1..10).step(2) { |i| print "#{i} " }
    puts ""
    

    Summary

    Ruby methods make your code reusable and easier to maintain. In this guide, you learned how to:

    • define and call methods
    • pass parameters and defaults
    • accept variable-length arguments
    • return values naturally
    • control method visibility (public/protected/private)
    • use recursion safely
    • use hook methods for metaprogramming
    • work with Ruby ranges

  • Ruby Control Statement

    Ruby Decision Making (if, if-else, if-else-if, ternary)

    Decision-making in programming is much like making choices in real life. In a program, certain blocks of code are executed based on whether a specific condition is true or false. Programming languages use control statements to manage the flow of execution depending on these conditions. These control structures guide the direction of execution, causing the program to branch or continue based on the current state. In Ruby, the if-else structure helps in testing these conditions.

    Types of Decision-Making Statements in Ruby:

    1. if statement
    2. if-else statement
    3. if-elsif ladder
    4. Ternary statement

    1. if Statement: In Ruby, the if statement determines whether a block of code should be executed based on a condition. If the condition evaluates to true, the associated code is executed.

    Syntax:

    if (condition)
       # code to be executed
    end

    Example:

    # Ruby program to demonstrate the if statement
    
    temperature = 30
    
    # Check if temperature is above 25 degrees
    if temperature > 25
      puts "It's a warm day."
    end

    Output:

    It's a warm day.

    2. if-else Statement: The if-else statement is used when one block of code should be executed if the condition is true, and another block should run if the condition is false.

    Syntax:

    if (condition)
        # code if the condition is true
    else
        # code if the condition is false
    end

    Example:

    # Ruby program to demonstrate if-else statement
    
    time = 16
    
    # Check if the time is past noon
    if time > 12
      puts "Good afternoon!"
    else
      puts "Good morning!"
    end

    Output:

    Good afternoon!

    3. if-elsif-else Ladder: This structure allows multiple conditions to be evaluated one after another. Once a true condition is found, the corresponding block of code is executed, and the remaining conditions are skipped.

    Syntax:

    if (condition1)
        # code if condition1 is true
    elsif (condition2)
        # code if condition2 is true
    else
        # code if neither condition1 nor condition2 is true
    end

    Example:

    # Ruby program to demonstrate if-elsif-else ladder
    
    score = 85
    
    if score < 50
      puts "You failed."
    elsif score >= 50 && score < 65
      puts "You passed with a C grade."
    elsif score >= 65 && score < 80
      puts "You passed with a B grade."
    elsif score >= 80 && score < 90
      puts "You passed with an A grade."
    else
      puts "You passed with an A+ grade."
    end

    Output:

    You passed with an A grade.

    4. Ternary Operator: The ternary operator is a shorthand for simple if-else statements. It evaluates a condition and returns one of two values based on whether the condition is true or false.

    Syntax:

    condition ? true_value : false_value

    Example:

    # Ruby program to demonstrate the ternary operator
    
    age = 20
    
    # Ternary operator to check if the person is an adult
    status = (age >= 18) ? "Adult" : "Minor"
    puts status

    Output:

    Adult

    Ruby Loops (for, while, do..while, until)

    Looping is an essential concept in programming, enabling the repeated execution of a block of code based on a specific condition. Ruby, a dynamic and flexible language, offers various looping constructs to handle iterations effectively. These loops help automate tasks that require repetitive actions within a program.

    The primary types of loops in Ruby include:

    1. while Loop
    2. for Loop
    3. do..while Loop
    4. until Loop

    1. while Loop: In a while loop, the condition is evaluated at the beginning of the loop, and the code block is executed as long as the condition is true. Once the condition becomes false, the loop terminates. This is known as an Entry-Controlled Loop since the condition is checked before executing the loop body. It’s commonly used when the number of iterations is unknown.

    Syntax:

    while condition [do]
      # code to be executed
    end

    Example:

    # Ruby program demonstrating the 'while' loop
    
    counter = 3
    
    # Using the while loop to print a message 3 times
    while counter > 0
      puts "Welcome to Ruby programming!"
      counter -= 1
    end

    Output:

    Welcome to Ruby programming!
    Welcome to Ruby programming!
    Welcome to Ruby programming!

    2. for Loop: The for loop in Ruby functions similarly to the while loop but has a more concise syntax, especially useful when the number of iterations is known in advance. It is often used to iterate over a range, array, or collection. This loop is also an Entry-Controlled Loop since the condition is evaluated before the loop begins.

    Syntax:

    for variable_name[, variable...] in expression [do]
      # code to be executed
    end

    Example:

    # Ruby program demonstrating the 'for' loop using a range
    
    for num in 1..4 do
      puts "Number: #{num}"
    end

    Output:

    Number: 1
    Number: 2
    Number: 3
    Number: 4

    Example 2: Iterating Over an Array

    # Ruby program demonstrating the 'for' loop with an array
    
    fruits = ["Apple", "Banana", "Cherry"]
    
    for fruit in fruits do
      puts fruit
    end

    Output:

    Apple
    Banana
    Cherry

    3. do..while Loop: The do..while loop is similar to the while loop, but with one key difference: the condition is evaluated after the code block has been executed, ensuring that the loop runs at least once. This makes it an Exit-Controlled Loop.

    Syntax:

    loop do
      # code to be executed
      break if condition
    end

    Example:

    # Ruby program demonstrating the 'do..while' loop
    
    counter = 0
    
    # The loop will run at least once
    loop do
      puts "Iteration #{counter + 1}"
      counter += 1
      break if counter == 3
    end

    Output:

    Iteration 1
    Iteration 2
    Iteration 3

    4. until Loop: The until loop in Ruby is the opposite of the while loop. It continues executing as long as the given condition remains false, and stops once the condition becomes true. Like while, this is also an Entry-Controlled Loop.

    Syntax:

    until condition [do]
      # code to be executed
    end

    Example:

    # Ruby program demonstrating the 'until' loop
    
    counter = 5
    
    # Using the until loop to print values until counter reaches 10
    until counter == 10 do
      puts counter
      counter += 1
    end

    Output:

    5
    6
    7
    8
    9

    5. Class Variables: Class variables start with @@ and are shared across all instances of a class. They belong to the class itself rather than any individual instance. Class variables must be initialized before they are used. An uninitialized class variable will raise an error.

    Example:

    # Ruby program to illustrate Class Variables
    
    class Library
      # Class variable
      @@book_count = 0
    
      def initialize(title)
        # Instance variable
        @title = title
      end
    
      def display_title
        puts "Book Title: #{@title}"
      end
    
      def add_book
        # Increment the class variable
        @@book_count += 1
        puts "Total books: #@@book_count"
      end
    end
    
    # Creating objects
    book1 = Library.new("The Art of Ruby")
    book2 = Library.new("Ruby on Rails Guide")
    
    # Calling methods
    book1.display_title
    book1.add_book
    
    book2.display_title
    book2.add_book

    Output:

    Book Title: The Art of Ruby
    Total books: 1
    Book Title: Ruby on Rails Guide
    Total books: 2

    6. Global Variables: Global variables start with a $ sign and are accessible from anywhere in the Ruby program. They are not limited to a specific class or scope. By default, an uninitialized global variable has a nil value. However, excessive use of global variables can make code difficult to debug and maintain.

    Example:

    # Ruby program to illustrate Global Variables
    
    # Global variable
    $global_count = 5
    
    class FirstClass
      def display_count
        puts "Global count in FirstClass: #$global_count"
      end
    end
    
    class SecondClass
      def display_count
        puts "Global count in SecondClass: #$global_count"
      end
    end
    
    # Creating objects
    obj1 = FirstClass.new
    obj2 = SecondClass.new
    
    # Calling methods
    obj1.display_count
    obj2.display_count

    Output:

    Global count in FirstClass: 5
    Global count in SecondClass: 5

    Case Statement Without a Value

    In Ruby, you can use a case statement without specifying a value. Instead, you can use the when clauses to evaluate different conditions directly.

    Example: Case Statement Without a Value

    # Ruby program demonstrating case statement without a value
    
    str = "HelloWorld123"
    
    # Case statement evaluating different conditions
    case
    when str.match(/\d/)
      puts "The string contains numbers."
    when str.match(/[a-zA-Z]/)
      puts "The string contains letters."
    else
      puts "The string contains neither letters nor numbers."
    end

    Example:

    The string contains numbers.

    Output:

    Global variable in FirstClass is 20
    Global variable in SecondClass is 20
    Case Statement in Method Call

    You can use a case statement directly in a method call, where it will return a value just like any other method.

    Example: Case Statement in a Method Call

    # Ruby program demonstrating case statement in a method call
    
    str = "4567"
    
    # Case statement inside a method call to return a value
    puts case
    when str.match(/\d/)
      "The string contains numbers."
    when str.match(/[a-zA-Z]/)
      "The string contains letters."
    else
      "The string contains neither numbers nor letters."
    end

    Output:

    The string contains numbers.

    Control Flow Statements in Ruby

    Ruby provides several control flow statements in addition to loops, conditionals, and iterators. These statements allow altering the normal execution flow in a program, controlling how the code is executed based on conditions or specific cases.

    Here’s a breakdown of some important Ruby control flow statements:

    1. break Statement: The break statement is used to exit a loop prematurely when a certain condition is met. Typically used in loops such as whilefor, and case statements, it stops the execution of the loop as soon as the condition becomes true.

    Syntax:

    break

    Example:

    # Ruby program demonstrating the break statement
    
    i = 1
    
    # Using a while loop
    while true
      if i * 6 >= 30
        break  # Exit the loop if condition is met
      end
    
      puts i * 6
      i += 1
    end

    Output:

    6
    12
    18
    24

    2.next Statement: The next statement is used to skip the current iteration and move to the next one in a loop. It’s similar to the continue statement in languages like C and Java.

    Syntax:

    next

    Example:

    # Ruby program demonstrating the next statement
    
    # Using a for loop
    for t in 0...10
      if t == 5
        next  # Skip the iteration when t is 5
      end
    
      puts t
    end

    Output:

    0
    1
    2
    3
    4
    6
    7
    8
    9

    3. redo Statement: The redo statement restarts the current iteration of the loop without testing the loop’s condition again. Unlike next, which skips to the next iteration, redo causes the loop to restart the current one.

    Syntax:

    redo

    Example:

    # Ruby program demonstrating the redo statement
    
    val = 0
    
    while val < 4
      puts val
      val += 1
    
      redo if val == 4  # Restart the loop when val equals 4
    end

    Output:

    0
    1
    2
    3
    4

    4.retry Statement (Deprecated): The retry statement was used in earlier versions of Ruby (before 1.9) to restart a loop or an iterator from the beginning. It has been removed in later versions, as it was considered a deprecated feature.

    5.return Statement: The return statement is used to exit a method and optionally pass a value back to the caller. If no value is provided, it returns nil.

    Example:

    # Ruby program demonstrating the return statement
    
    def my_method
      val1 = 100
      val2 = 200
    
      return val1, val2  # Returning multiple values
    
      puts "This won't be executed"
    end
    
    result = my_method
    puts result

    Output:

    100
    200

    6. throw/catch Statement: The throw and catch statements are used to create an advanced control flow structure. It’s like a multi-level break that allows you to exit out of deeply nested loops or methods. throw is used to break out, while catch defines a label where control can be transferred.

    Example:

    # Ruby program demonstrating throw/catch control flow
    
    def check_number(num)
      throw :error if num < 10  # Exit the block if number is less than 10
      puts "Number is greater than or equal to 10!"
    end
    
    catch :error do
      check_number(15)
      check_number(25)
      check_number(5)  # This will cause the throw statement to exit the block
    end
    
    puts "Code after catch block"

    Output:

    Number is greater than or equal to 10!
    Number is greater than or equal to 10!
    Code after catch block

    Break and Next Statement

    Break statement: 

    In Ruby, the break statement is used to stop the execution of a loop prematurely. It is often applied in loops like while and for, where it helps to exit the loop when a specific condition is met. Once the condition triggers the break statement, the loop terminates, and the code continues after the loop.

    Syntax:

    break

    Example:

    # Ruby program demonstrating the break statement
    i = 1
    
    # Using a while loop
    while true
      puts i * 3  # Print multiples of 3
      i += 1
      if i * 3 >= 21
        break  # Exit the loop if the condition is met
      end
    end

    Output:

    3
    6
    9
    12
    15
    18

    Explanation: In this example, the loop prints multiples of 3. Once the value i * 3 becomes 21 or greater, the break statement stops the loop.

    Example:

    # Another example demonstrating break statement
    x = 0
    
    # Using a while loop
    while true
      puts x  # Print current value of x
      x += 1
      break if x > 3  # Stop the loop when x becomes greater than 3
    end

    Output:

    0
    1
    2
    3
    next Statement in Ruby

    The next statement is used to skip the rest of the current loop iteration and immediately proceed to the next iteration. It’s similar to the continue statement in other programming languages like C or Python. This is useful when certain conditions inside a loop should cause the loop to skip to the next step without executing further code for that iteration.

    Syntax:

    next

    Example:

    # Ruby program demonstrating the next statement
    for x in 0..6
      if x + 1 < 4
        next  # Skip the current iteration if the condition is met
      end
    
      puts "Value of x is: #{x}"  # Print the value of x for other cases
    end

    Output:

    Value of x is: 3
    Value of x is: 4
    Value of x is: 5
    Value of x is: 6

    Working with Directories in Ruby

    directory is a location where files can be stored. In Ruby, the Dir class and the FileUtils module provide various methods for managing directories, while the File class handles file operations. Double dot (..) refers to the parent directory, and single dot (.) refers to the current directory itself.

    The Dir Class

    The Dir class allows access to and manipulation of directory structures in Ruby. It includes methods for listing directory contents, creating directories, changing directories, and more.

    Features of the Dir Class

    1. Creating Directories: The mkdir method is used to create a new directory. It returns 0 if the directory is successfully created.

    Syntax:

    next

    Examples:

    # Ruby program demonstrating the next statement
    for x in 0..6
      if x + 1 < 4
        next  # Skip the current iteration if the condition is met
      end
    
      puts "Value of x is: #{x}"  # Print the value of x for other cases
    end

    Output:

    Value of x is: 3
    Value of x is: 4
    Value of x is: 5
    Value of x is: 6

    Ruby redo and retry Statement

    redo statement:

    The redo statement in Ruby is used to repeat the current iteration of a loop without re-evaluating the loop condition. It is useful when you want to retry the current iteration based on a specific condition. This statement can only be used inside loops.

    Syntax:

    redo

    Example:

    # Ruby program demonstrating redo statement
    restart = false
    
    # Using a for loop
    for x in 2..20
      if x == 15
        if restart == false
          # Print message when x is 15 for the first time
          puts "Re-doing when x = #{x}"
          restart = true
    
          # Using redo statement to repeat the current iteration
          redo
        end
      end
      puts x
    end

    Output:

    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    Re-doing when x = 15
    15
    16
    17
    18
    19
    20
    retry Statement in Ruby

    The retry statement is used to restart the entire loop from the beginning. It is typically used within a block that includes begin-rescue error handling. The control jumps back to the start of the block or the loop, retrying the entire process. As of Ruby 1.9, the retry statement is considered deprecated for regular loops but is still available in begin-rescue blocks for exception handling.

    Example :

    # Ruby program demonstrating retry statement
    
    # Using a do loop
    10.times do |i|
      begin
        puts "Iteration #{i}"
        raise if i > 2  # Raise an exception if i is greater than 2
      rescue
        # Retry the iteration if an exception is raised
        retry
      end
    end

    Output:

    Iteration 0
    Iteration 1
    Iteration 2
    Iteration 3
    Iteration 3
    Iteration 3
    ...
  • Ruby Basic Concepts

    Ruby Keywords

    Keywords or reserved words are special words in a programming language that have predefined meanings and are used for certain internal processes. These words cannot be used as identifiers such as variable names, object names, or constants. Attempting to use these reserved words as identifiers will result in a compile-time error.

    Example of Invalid Use of Keywords

    # Ruby program to illustrate Keywords
    
    # This is an incorrect use of the keyword 'if'
    # It cannot be used as a variable name
    if = 30
    
    # Here 'if' and 'end' are keywords used incorrectly
    # Using them will result in a syntax error
    if if >= 18
      puts "You are eligible to drive."
    end

    Compile-Time Error:

    Error(s), warning(s):
    
    example.rb:4: syntax error, unexpected '='
    
    if = 30
    
        ^
    
    example.rb:9: syntax error, unexpected '>='
    
    if if >= 18
    
            ^
    
    example.rb:11: syntax error, unexpected keyword_end, expecting end-of-input
    Common Ruby Keywords

    Ruby has a total of 41 reserved keywords. Here are some of the most common ones and their uses:

    KeywordDescription
    __ENCODING__The script encoding of the current file.
    __LINE__The line number in the current file.
    __FILE__The path to the current file.
    BEGINRuns code before any other in the current file.
    ENDRuns code after all other code in the current file.
    aliasCreates an alias for a method.
    andLogical AND with lower precedence than &&.
    classDefines a new class.
    defDefines a method.
    doBegins a block of code.
    endEnds a syntax block such as a class, method, or loop.
    ifConditional statement.
    moduleDefines a module.
    nextSkips to the next iteration of a loop.
    nilRepresents “no value” or “undefined”.
    returnExits from a method and optionally returns a value.
    selfRefers to the current object.
    trueBoolean true value.
    whileCreates a loop that executes while a condition is true.

    Example of Using Keywords Correctly

    Here’s a simple example demonstrating the correct use of some Ruby keywords:

    # Ruby program to illustrate the use of Keywords
    
    #!/usr/bin/ruby
    
    # Defining a class named 'Person'
    class Person
    
      # Defining a method using 'def' keyword
      def introduce
        # Printing a statement using 'puts'
        puts "Hello! I'm learning Ruby."
      end
    
    # End of the method
    end
    
    # End of the class
    end
    
    # Creating an object of the class 'Person'
    student = Person.new
    
    # Calling the method using the object
    student.introduce

    Output:

    Hello! I'm learning Ruby.

    Ruby Data Types

    In Ruby, data types represent various kinds of data such as text, numbers, symbols, arrays, etc. Since Ruby is a pure Object-Oriented Language, all data types are based on classes. Here are the primary data types in Ruby:

    1. Numbers
    2. Boolean
    3. Strings
    4. Hashes
    5. Arrays
    6. Symbols

    1. Numbers: A number is generally defined as a sequence of digits, which may include a dot for decimal places. Ruby supports both integer and floating-point numbers. Depending on their size, numbers can be categorized into Fixnum and Bignum. However, in modern Ruby versions, they have been unified under the Integer class.

    Example:

    # Ruby program to illustrate Numbers Data Type
    
    # Float type
    distance = 0.2
    
    # Both integer and float type
    time = 15.0 / 3600
    speed = distance / time
    puts "The average speed of the cyclist is #{speed} km/h"

    Output:

    The average speed of the cyclist is 48.0 km/h

    2. Boolean: The Boolean data type represents two values: true or false. This data type is used for simple true/false conditions.

    Example:

    # Ruby program to illustrate Boolean Data Type
    
    if false
      puts "This won't be printed!"
    else
      puts "This is False!"
    end
    
    if nil
      puts "nil is True!"
    else
      puts "nil is False!"
    end
    
    if 1
      puts "1 is True!"
    else
      puts "1 is False!"
    end

    Output:

    This is False!
    nil is False!
    1 is True!

    3. Strings: A string is a collection of characters enclosed within either single (') or double (") quotes. Double-quoted strings allow for string interpolation and special character sequences, while single-quoted strings only support limited escape sequences.

    Example:

    # Ruby program to illustrate Strings Data Type
    
    puts "Ruby String Data Type"
    puts 'Escape using "\\"'
    puts 'It\'s a beautiful day!'

    Output:

    Ruby String Data Type
    Escape using "\"
    It's a beautiful day!

    4. Hashes: A hash is a collection of key-value pairs, similar to a dictionary in Python or an associative array in PHP. Keys and values are separated by => and each pair is enclosed within curly braces {}.

    Example:

    # Ruby program to illustrate Hashes Data Type
    
    colors = { "red" => "#FF0000", "green" => "#00FF00", "blue" => "#0000FF" }
    colors.each do |color, hex|
      puts "#{color} has hex value #{hex}"
    end

    Output:

    red has hex value #FF0000
    green has hex value #00FF00
    blue has hex value #0000FF

    5. Arrays: An array is an ordered collection of elements, which can contain data of any type. Elements are separated by commas and enclosed within square brackets []. Arrays in Ruby can hold mixed data types.

    Example

    # Ruby program to illustrate Arrays Data Type
    
    data = ["Alice", 25, 5.5, "Hello, world!", "last item"]
    data.each do |element|
      puts element
    end

    Output:

    Alice
    25
    5.5
    Hello, world!
    last item

    6. Symbols: Symbols are lightweight, immutable strings. They are used instead of strings in situations where memory optimization is crucial. A symbol is prefixed with a colon (:).

    Example:

    # Ruby program to illustrate Symbols Data Type
    
    countries = { :us => "United States", :ca => "Canada", :fr => "France" }
    
    puts countries[:us]
    puts countries[:ca]
    puts countries[:fr]

    Output:

    United States
    Canada
    France

    Types of Variables in Ruby

    In Ruby, there are four main types of variables, each serving different purposes and having different scopes. Each type is distinguished by a special character at the beginning of the variable name.

    SymbolType of Variable
    [a-z] or _Local Variable
    @Instance Variable
    @@Class Variable
    $Global Variable

    1. Local Variables: Local variables in Ruby start with a lowercase letter (a-z) or an underscore (_). They are restricted to the scope in which they are defined (e.g., inside a method or a block). Local variables do not need to be initialized before use.

    Example:

    # Ruby program to illustrate Local Variables
    
    # Local variables
    name = "Alice"
    _age = 30
    
    puts "Name: #{name}"
    puts "Age: #{_age}"

    Output:

    Name: Alice
    Age: 30

    2. Instance Variables: Instance variables start with an @ sign. They belong to a specific instance of a class and are accessible across different methods within that instance. Each instance of the class can have different values for its instance variables. Uninitialized instance variables have a nil value by default.

    Example:

    # Ruby program to illustrate Instance Variables
    
    class Book
      def initialize(title, author)
        # Instance variables
        @title = title
        @auth_name = author
      end
    
      def display_info
        puts "Title: #{@title}"
        puts "Author: #{@auth_name}"
      end
    end
    
    # Creating objects
    book1 = Book.new("Ruby Programming", "John Doe")
    book2 = Book.new("Learning Ruby", "Jane Doe")
    
    # Calling methods
    book1.display_info
    book2.display_info

    Output:

    Title: Ruby Programming
    Author: John Doe
    Title: Learning Ruby
    Author: Jane Doe

    3. Class Varia: Class variables start with @@ and are shared across all instances of a class. They belong to the class itself rather than any individual instance. Class variables must be initialized before they are used. An uninitialized class variable will raise an error.

    Example:

    # Ruby program to illustrate Class Variables
    
    class Library
      # Class variable
      @@book_count = 0
    
      def initialize(title)
        # Instance variable
        @title = title
      end
    
      def display_title
        puts "Book Title: #{@title}"
      end
    
      def add_book
        # Increment the class variable
        @@book_count += 1
        puts "Total books: #@@book_count"
      end
    end
    
    # Creating objects
    book1 = Library.new("The Art of Ruby")
    book2 = Library.new("Ruby on Rails Guide")
    
    # Calling methods
    book1.display_title
    book1.add_book
    
    book2.display_title
    book2.add_book

    Output:

    Book Title: The Art of Ruby
    Total books: 1
    Book Title: Ruby on Rails Guide
    Total books: 2

    4. Global Variables: Global variables start with a $ sign and are accessible from anywhere in the Ruby program. They are not limited to a specific class or scope. By default, an uninitialized global variable has a nil value. However, excessive use of global variables can make code difficult to debug and maintain.

    Example:

    # Ruby program to illustrate Global Variables
    
    # Global variable
    $global_count = 5
    
    class FirstClass
      def display_count
        puts "Global count in FirstClass: #$global_count"
      end
    end
    
    class SecondClass
      def display_count
        puts "Global count in SecondClass: #$global_count"
      end
    end
    
    # Creating objects
    obj1 = FirstClass.new
    obj2 = SecondClass.new
    
    # Calling methods
    obj1.display_count
    obj2.display_count

    Output:

    Global count in FirstClass: 5
    Global count in SecondClass: 5

    Global Variable in Ruby

    Global variables have a global scope, meaning they are accessible from anywhere in a program. Modifying global variables from any point in the code has implications across the entire program. Global variables are always denoted with a dollar sign ($). If a variable needs to be shared across multiple classes, defining it as a global variable ensures it can be accessed from all classes. By default, an uninitialized global variable has a nil value, which can lead to confusing and complex code. Global variables can be modified from any part of the program.

    Syntax:

    $global_variable = 5

    Example:

    # Ruby program demonstrating global variables
    
    # Defining a global variable
    $global_variable = 20
    
    # Defining first class
    class FirstClass
      def display_global
        puts "Global variable in FirstClass is #$global_variable"
      end
    end
    
    # Defining second class
    class SecondClass
      def display_global
        puts "Global variable in SecondClass is #$global_variable"
      end
    end
    
    # Creating instances of both classes
    first_instance = FirstClass.new
    first_instance.display_global
    
    second_instance = SecondClass.new
    second_instance.display_global

    Output:

    Global variable in FirstClass is 20
    Global variable in SecondClass is 20

    In the above example, a global variable is defined with the value 20, and it can be accessed in both classes.

    Another Example:

    # Ruby program to demonstrate global variables across methods and classes
    
    $global_variable1 = "Hello"
    
    class SampleClass
      def show_global_in_instance_method
        puts "Global variables are accessible here: #{$global_variable1}, #{$another_global_var}"
      end
    
      def self.set_global_in_class_method
        $another_global_var = "World"
        puts "Global variables are accessible here: #{$global_variable1}"
      end
    end
    
    # Using the class method
    SampleClass.set_global_in_class_method
    
    # Creating an object and using the instance method
    sample_object = SampleClass.new
    sample_object.show_global_in_instance_method

    Output:

    Global variables are accessible here: Hello
    Global variables are accessible here: Hello, World

    Literal

    In Ruby, a literal is any constant value that can be assigned to a variable. We use literals whenever we type an object directly into the code. Ruby literals are similar to those in other programming languages, with some differences in syntax and functionality.

    Types of Ruby Literals

    Ruby supports various types of literals:

    1. Booleans and nil
    2. Numbers
    3. Strings
    4. Symbols
    5. Ranges
    6. Arrays
    7. Hashes
    8. Regular Expressions

    1. Booleans and nil: Booleans are constants that represent the truth values true and falsenil is another constant that represents an “unknown” or “empty” value, and it behaves similarly to false in conditional expressions.

    Example:

    # Boolean literals demonstration
    puts(5 + 2 == 7)  # true
    puts(5 - 3 != 2)  # false
    puts(nil == false)  # false

    Output:

    true
    false
    false

    2. Numbers: Ruby supports different types of numbers, including integers and floating-point numbers. You can write numbers of any size, using underscores (_) for readability. Ruby allows various numerical formats, including decimal, hexadecimal, octal, and binary.

    Example:

    # Number literals demonstration
    puts("Sum: ", 100 + 2_00 + 300)  # underscores for readability
    puts("Hexadecimal:", 0x1A)  # hexadecimal
    puts("Octal:", 0o56)  # octal
    puts("Decimal:", 123)  # decimal
    puts("Binary:", 0b1101)  # binary
    puts("Float:", 1.234E2)  # scientific notation

    Output:

    Sum: 600
    Hexadecimal: 26
    Octal: 46
    Decimal: 123
    Binary: 13
    Float: 123.4

    3. Strings: Strings in Ruby can be enclosed in either double quotes (" ") or single quotes (' '). Double-quoted strings support interpolation and special characters, while single-quoted strings only support limited escape sequences.

    Example:

    # String literals demonstration
    puts("The result of 3 + 4 is: #{3 + 4}")  # string interpolation
    puts("Hello\nWorld")  # new line in double quotes
    puts('Hello\nWorld')  # no new line in single quotes

    Output:

    The result of 3 + 4 is: 7
    Hello
    World
    Hello\nWorld

    4. Symbols: symbol in Ruby is a lightweight, immutable string used as an identifier. Symbols are created using a colon (:) and are never garbage-collected, making them memory-efficient for repeated use.

    Example:

    # Symbol demonstration
    puts(:user_id)  # simple symbol
    puts(:"user#{42}")  # symbol with interpolation

    Output:

    user_id
    user42

    5. Ranges: Ranges represent a set of values between a starting and an ending point. They can include numbers, characters, or other objects. Ranges can be constructed using the .. (inclusive) or ... (exclusive) operators.

    Example:

    # Range literals demonstration
    for i in 1..4 do
      puts(i)
    end
    
    puts("Exclusive range:", (1...4).to_a)

    Output:

    1
    2
    3
    4
    Exclusive range: [1, 2, 3]

    6. Arrays: An array is a collection of objects in Ruby, enclosed within square brackets ([ ]). Arrays can contain objects of different data types, and elements are separated by commas.

    Example:

    # Array demonstration
    fruits = ['apple', 'banana', 'cherry']
    puts(fruits[0])  # accessing the first element
    puts(fruits[1..2])  # accessing a range of elements
    puts("Negative index:", fruits[-1])  # accessing the last element

    Output:

    apple
    banana
    cherry
    Negative index: cherry

    7. Hashes: hash is a collection of key-value pairs, similar to dictionaries in other languages. Hashes are defined using curly braces ({ }), and symbols can be used as keys for efficiency.

    Example:

    # Hash demonstration
    person = { name: "Alice", age: 30, city: "Wonderland" }
    
    # Accessing hash elements
    puts(person[:name])
    puts(person[:age])
    
    # Iterating over the hash
    person.each do |key, value|
      puts("#{key} => #{value}")
    end

    Output:

    Alice
    30
    name => Alice
    age => 30
    city => Wonderland

    8. Regular Expressions: Ruby supports regular expressions (regex) for pattern matching. Regular expressions are defined using forward slashes (/pattern/) or %r{pattern}.

    Example:

    # Regular expression demonstration
    line1 = "The quick brown fox"
    line2 = "Jumps over the lazy dog"
    
    # Checks if 'quick' is in line1
    if (line1 =~ /quick/)
      puts line1
    end
    
    # Checks if 'lazy' is in line2 using %r{} format
    if (line2 =~ %r{lazy})
      puts line2
    end
    
    # Checks if 'rabbit' is in line2
    if (line2 =~ /rabbit/)
      puts line2
    else
      puts "No match found"
    end

    Output:

    The quick brown fox
    Jumps over the lazy dog
    No match found

    Ruby Directories

    Working with Directories in Ruby

    directory is a location where files can be stored. In Ruby, the Dir class and the FileUtils module provide various methods for managing directories, while the File class handles file operations. Double dot (..) refers to the parent directory, and single dot (.) refers to the current directory itself.

    The Dir Class

    The Dir class allows access to and manipulation of directory structures in Ruby. It includes methods for listing directory contents, creating directories, changing directories, and more.

    Features of the Dir Class

    1. Creating Directories: The mkdir method is used to create a new directory. It returns 0 if the directory is successfully created.

    Syntax:

    Dir.mkdir "directory_name"

    Examples:

    # Creating a directory named "my_folder"
    result = Dir.mkdir "my_folder"
    
    # Output the result
    puts result

    Output:

    2. Checking Directories: The exist? method checks if a directory exists.

    Syntax:

    Dir.exist? "directory_name"

    Example:

    # Create a directory named "my_folder"
    Dir.mkdir("my_folder")
    
    # Check if the directory exists
    puts Dir.exist?("my_folder")

    Output:

    true
    • The empty? method checks if a directory is empty.

    Syntax:

    Dir.empty? "directory_name"

    3. Working with Directories

    • The new method creates a new directory object (the directory should already exist).

    Syntax:

    obj = Dir.new("directory_name")
    • The pwd method returns the current working directory.

    Syntax:

    Dir.pwd

    Example:

    # Create a directory named "example_folder"
    Dir.mkdir("example_folder")
    
    # Print the current working directory
    puts Dir.pwd

    Output:

    /path/to/current/directory
    • The home method returns the home directory of the current user.

    Syntax:

    Dir.home

    Example:

    # Print the home directory
    puts Dir.home

    Output:

    /Users/username
    • The path method returns the path of a directory object.

    Syntax:

    d = Dir.new("directory_name")
    d.path

    Output:

    Odd

    Example:

    # Create a directory and get its path
    Dir.mkdir("example_folder")
    obj = Dir.new("example_folder")
    puts obj.path

    Output:

    example_folder
    • The getwd method returns the path of the current directory.

    Syntax:

    Dir.getwd

    Example:

    /path/to/current/directory
    • The chdir method changes the current working directory.

    Syntax:

    Dir.chdir("directory_name")

    Example:

    # Create directories
    Dir.mkdir("/workspace/folder1")
    Dir.mkdir("/workspace/folder2")
    
    # Change to folder2
    Dir.chdir("/workspace/folder2")
    puts Dir.pwd

    Output:

    /workspace/folder2
    • The entries method lists all files and folders in a directory.

    Syntax:

    Dir.entries("directory")

    Example:

    # Create a directory and subdirectories
    Dir.mkdir("main_folder")
    Dir.chdir("main_folder")
    Dir.mkdir("subfolder1")
    Dir.mkdir("subfolder2")
    
    # List all files and folders
    puts Dir.entries(".")

    Output:

    .
    ..
    subfolder1
    subfolder2
    • The glob method lists files matching a certain pattern.

    Syntax:

    Dir.glob("pattern")

    Example:

    # Create files and folders
    Dir.mkdir("sample_folder")
    Dir.chdir("sample_folder")
    Dir.mkdir("test")
    Dir.mkdir("demo.rb")
    Dir.mkdir("script.rb")
    
    # List files matching patterns
    puts Dir.glob("*.rb")

    Output:

    demo.rb
    script.rb

    4. Removing Directories: Methods like rmdirdelete, and unlink are used to remove directories.

    Syntax:

    Dir.delete "directory_name"
    Dir.rmdir "directory_name"
    Dir.unlink "directory_name"

    Example:

    # Create a directory
    Dir.mkdir("temp_folder")
    puts Dir.exist?("temp_folder")
    
    # Remove the directory
    Dir.rmdir("temp_folder")
    puts Dir.exist?("temp_folder")

    Output:

    true
    false

    5. Creating Nested Directories: The mkdir_p method from the FileUtils module creates a directory and all its parent directories.

    Syntax:

    FileUtils.mkdir_p 'directory_path'

    Example:

    require "fileutils"
    
    # Create nested directories
    FileUtils.mkdir_p "parent/child/grandchild"
    
    # Check existence
    Dir.chdir("parent/child")
    puts Dir.exist?("grandchild")

    Output:

    true

    6. Moving Files and Folders: The mv method from the FileUtils module is used to move files or directories.

    Syntax:

    FileUtils.mv("source", "destination")

    Example:

    require "fileutils"
    
    # Create directories
    Dir.mkdir "source_folder"
    Dir.mkdir "destination_folder"
    
    # Move source_folder into destination_folder
    FileUtils.mv("source_folder", "destination_folder")
    
    # Check if the move was successful
    Dir.chdir("destination_folder")
    puts Dir.exist?("source_folder")

    Output:

    true

    7. Copying Files: The cp method from the FileUtils module copies files from one location to another.

    Syntax:

    FileUtils.cp("source", "destination")

    Example:

    require "fileutils"
    
    # Copy file.txt from source_folder to destination_folder
    FileUtils.cp("source_folder/file.txt", "destination_folder")
    
    # Check if the file exists in the destination
    Dir.chdir("destination_folder")
    puts File.exist?("file.txt")

    Output:

    true
  • Ruby Overview

    Ruby is a pure object-oriented programming language created by Yukihiro Matsumoto, commonly known as Matz within the Ruby community, in the mid-1990s in Japan. In Ruby, almost everything is treated as an object, with the exception of blocks, which can be replaced by constructs like procs and lambdas. The main goal behind Ruby’s development was to create a language that acts as an intuitive bridge between human programmers and the underlying computing systems. Ruby’s syntax bears resemblance to languages such as C and Java, making it easy for developers from those backgrounds to pick up. It runs across various platforms, including Windows, Mac, and Linux.

    Ruby draws inspiration from multiple programming languages, including Perl, Lisp, Smalltalk, Eiffel, and Ada. It is an interpreted scripting language, meaning its instructions are executed directly, without the need for prior compilation into machine code. Ruby programmers also benefit from access to RubyGems, a package manager providing a standard format for distributing Ruby libraries and applications.

    Getting Started with Ruby Programming

    1. Finding a Compiler:
    Before you can start coding in Ruby, you need a compiler to run your programs. There are many online Ruby compilers that allow you to begin programming without installation:

    • JDoodle
    • Repl.it

    2. Writing a Ruby Program:
    Ruby is easy to learn, particularly for those familiar with other common programming languages, due to its similar syntax.

    Writing Ruby Programs:
    You can write Ruby code in any text editor, such as Notepad++ or gedit. Once the code is written, save the file with the .rb extension.

    Key Concepts:

    • Comments: Single-line comments in Ruby are created using the # symbol.Example:
    fun main() {
        println("Hello World")
    }
    Key Features of Kotlin:

    1. Statically Typed: In Kotlin, the type of every variable and expression is determined at compile time. Although it is a statically typed language, it doesn’t require you to explicitly define the type for every variable.

    2. Data Classes: Kotlin includes Data Classes that automatically generate boilerplate code such as equals, hashCode, toString, and getters/setters. For example:

    Java Code:

    class Book {
        private String title;
        private Author author;
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public Author getAuthor() {
            return author;
        }
    
        public void setAuthor(Author author) {
            this.author = author;
        }
    }

    Kotlin Code:

    data class Book(var title: String, var author: Author)
    • Conciseness: Kotlin significantly reduces the amount of code required compared to other object-oriented programming languages.
    • Safety: Kotlin helps prevent the notorious NullPointerExceptions by incorporating nullability into its type system. By default, every variable in Kotlin is non-null.
    val s: String = "Hello World" // Non-null
    // The following line will produce a compile-time error:
    // s = null

    Output:

    Hello, World! Welcome to Ruby Programming.
    Advantages of Ruby
    • Concise and Elegant Code: Ruby allows you to write clean, efficient, and powerful code in fewer lines compared to many other programming languages.
    • Rapid Web Development: Ruby excels at web development, reducing the effort required to build applications quickly.
    • Open Source: Ruby is free to use, modify, and distribute, providing flexibility to developers to make necessary changes.
    • Dynamic Language: Ruby’s dynamic nature allows developers to implement features without rigid constraints, and its syntax closely resembles natural language.
    Disadvantages of Ruby
    • Learning Curve: Ruby has a unique syntax that may take time for programmers to get accustomed to, especially those who are used to other languages.
    • Debugging Challenges: Since Ruby is dynamically typed and many errors occur at runtime, debugging can be more challenging compared to statically typed languages.
    • Limited Resources: Ruby doesn’t have as many learning materials and community resources compared to more established languages like Python or Java.
    • Performance: As Ruby is an interpreted language, it tends to be slower than compiled languages like C++ or Java.

    Comparison of Java with other programming languages

    Python vs. Java
    • High-Level Language: Python is a high-level programming language that fully supports object-oriented programming, though it is not a pure object-oriented language.
    • Interpretation vs. Compilation: Python is an interpreted language, whereas Java is compiled, giving Java an edge in performance.
    • Scripting Language: Python is classified as a scripting language, while Java is considered a low-level implementation language.
    • Ease of Use: Python’s syntax is simple and concise, which makes it easier to learn and use compared to Java. Python programs typically require fewer lines of code, while Java can be more verbose.
    • Popularity: Python is widely used in industries for various projects because of its simplicity, while Java’s complexity can make it more challenging, though it remains popular for large-scale applications.
    • Dynamic Typing: Python supports dynamic typing, allowing developers to save time by writing less code. In contrast, Java requires static typing, where the type of each variable must be defined before use.
    • Performance: Python programs generally run slower than Java programs, but Python is often chosen for rapid prototyping and projects with faster development timelines.
    • Library Support: Java provides extensive libraries that are better suited for certain use cases, especially when performance and security are priorities.
    C++ vs. Java
    • Language Paradigm: C++ is both a procedural and object-oriented language, while Java is strictly object-oriented.
    • Different Objectives: C++ is designed primarily for system-level programming, whereas Java is designed with cross-platform network computing in mind.
    • Operator Overloading: Java does not support operator overloading, while C++ does.
    • Memory Management: Java features automatic garbage collection, whereas in C++, memory management is manual, requiring developers to destroy objects explicitly.
    • Execution Speed: C++ generally runs faster than Java due to its closer proximity to machine code.
    • Libraries: C++ libraries are more focused on system-level tasks, while Java’s cross-platform libraries provide robust support for a wide variety of applications.
    • Pointers: C++ allows for the use of pointers (variables that store memory addresses), which Java intentionally omits to reduce complexity and improve security.
    Ruby vs. Java
    • Typing: Java is statically typed, requiring explicit declaration of variable types, while Ruby is dynamically typed, allowing more flexibility but potentially leading to more runtime errors.
    • Code Execution: Java code is compiled into bytecode and run on the Java Virtual Machine (JVM), making it faster in execution compared to Ruby’s interpreted nature.
    • Code Efficiency: Ruby allows for more concise code, requiring fewer lines than Java for similar functionality, which is why Ruby is often favored for rapid development.
    • Inheritance and Access Modifiers: Both Java and Ruby support inheritance and include public, private, and protected methods, but Ruby’s dynamic typing often results in simpler, more flexible code.
    C vs. Java
    • Procedural vs. Object-Oriented: C is a procedural language that focuses on structured programming, while Java follows the object-oriented paradigm.
    • Execution Speed: Programs written in C generally execute faster than those in Java, as C compiles directly to machine code.
    • Pointer Support: C supports pointers, a feature that Java omits to improve safety and simplify memory management.
    • Exception Handling: Java has robust exception handling mechanisms, which C lacks, making error management in Java programs more efficient and user-friendly.

    Similarities Between Ruby and C

    Despite their differences, Ruby and C share several key similarities, including:

    1. Procedural Programming: Both languages allow programmers to write code procedurally if desired, even though Ruby operates in an object-oriented manner behind the scenes.
    2. Common Operators: Both Ruby and C use similar operators such as compound assignment and bitwise operators. However, Ruby lacks the ++ and — operators that are present in C.
    3. Special Variables: Both languages provide special variables like __FILE__ and __LINE__.
    4. Constants: While neither language uses a specific const keyword, both support the use of constants.
    5. String Notation: In both languages, strings are written within double quotes, e.g., “Hello”.
    6. Mutable Strings: Both Ruby and C feature mutable strings, allowing modification after creation.
    Documentation: Ruby’s ri command functions similarly to the man pages in C, offering a way to view documentation directly in the terminal.
    Debuggers: Both languages feature similar command-line debuggers.

    Differences Between Ruby and C

    Though they share similarities, Ruby and C differ significantly in various aspects:

    RubyC
    Code does not need to be compiled; it can be executed directly.Code must be compiled before it can be executed.
    Ruby uses require 'foo' instead of #include or #include "foo".C uses #include to include files or libraries.
    Variables do not need to be declared before use.Variables must be declared before use.
    Ruby lacks macros, a pre-processor, casts, pointers, typedefs, sizeof, and enums.C includes all these features.
    Arguments to methods (functions) are passed by value, with values always being object references.C allows passing function arguments by value and by reference.
    Parentheses around method calls are often optional.Parentheses are required for function calls in C.
    Ruby does not have a char type—single characters are treated as 1-letter strings.C uses the char data type to represent single characters.
    Array literals are enclosed in square brackets.Array literals are enclosed in curly braces.
    Ruby does not allow dropping down to assembly.C allows dropping down to assembly for low-level operations.
    Objects in Ruby are strongly typed.Objects in C are not strongly typed.
    Parentheses are optional in if and while conditionals.Parentheses are required for conditionals in C.
    Strings do not end with a null byte.Strings in C are null-terminated (end with a null byte).
    Adding two arrays creates a new array, instead of using pointer arithmetic.Pointer arithmetic is required when working with arrays.
    Ruby arrays automatically expand as elements are added.C arrays have fixed sizes and do not grow automatically.
    Variables live on the heap, and the garbage collector handles memory management.Memory must be manually allocated and deallocated in C, as there is no garbage collector.
    Multi-line constructs like loops are closed using the end keyword, with no braces.Braces {} are required to enclose multi-line blocks in C.
    Ruby lacks header files; all functions and classes are defined directly in the source code.C uses header files to declare functions and types.
    No semicolons are required to end lines.Lines must end with a semicolon in C.
    Ruby has no #define directive; constants are used instead.C uses #define for macros and constants.
    The do keyword is used for Ruby “blocks”, but there is no do statement as in C.C uses the do keyword with while to form do-while loops.

    Similarities and Differences between Ruby and C++ language

    C++ and Ruby share several similarities, including the following:

    Differences Between Ruby and C++

    RubyC++
    In Ruby, variables are automatically dereferenced, meaning they point directly to objects without needing explicit references or pointers.In C++, references and pointers are explicitly used to handle objects and their addresses.
    Ruby was created by Yukihiro Matsumoto (Matz) and first released in 1996.C++ was introduced by Bjarne Stroustrup in 1979 as an extension of the C language, with the first official release in 1985.
    Ruby uses dynamic typing, where variables can hold objects of any type, and their types are checked at runtime.C++ employs static typing, meaning variable types must be declared explicitly, and types are checked at compile time.
    In Ruby, constructors are always named initialize, regardless of the class name.C++ constructors are named after the class itself, with no fixed keyword for them.
    Ruby primarily relies on two container types, Arrays and Hashes.C++ offers a wide range of container types, including vectors, lists, maps, and more through the Standard Template Library (STL).
    Ruby doesn’t require templates or casting.C++ uses templates for generic programming and often requires explicit casting between types.
    Ruby uses self to refer to the current instance of an object.In C++, this is used to refer to the current object.
    Iteration in Ruby is done using built-in iterator methods, often combined with code blocks.In C++, iteration is typically done using iterators or looping structures like for or while loops.
    Ruby includes a standard unit testing framework (lib) as part of the language.C++ does not come with a built-in unit testing framework, though many external libraries are available.
    Ruby doesn’t perform type conversion, relying on dynamic typing and flexibility with data types.C++ often requires explicit type conversion to ensure proper handling of variable types.
    Ruby enforces some naming conventions for methods and variables, like using snake_case.C++ does not enforce any specific naming conventions, allowing developers to choose their style.
    In Ruby, classes can be reopened at any time to add or modify methods dynamically.C++ classes cannot be reopened once defined; all methods and attributes must be declared upfront.
    Ruby methods can end with special characters like ? (for queries) or ! (for methods that modify the object).C++ methods do not use special symbols like ? or ! in their names.
    All methods in Ruby are virtual, allowing for polymorphism without additional syntax.In C++, methods must be explicitly declared as virtual to support polymorphism.
    Ruby has built-in support for multithreading, although early versions (e.g., 1.8) used green threads.C++ does not include multithreading as part of the core language, though it can be implemented using libraries.
    In Ruby, parentheses for method calls are optional, making the syntax more flexible.C++ requires parentheses for all function and method calls, regardless of context.
    Ruby prohibits direct access to member variables; all access must go through getter and setter methods.In C++, member variables can be accessed directly unless they are explicitly made private or protected.
    Ruby is predominantly used for web development, automation, and scripting.C++ is widely used for systems programming, game development, embedded systems, and large-scale applications.
    Ruby runs on platforms like Linux, macOS, and Solaris.C++ supports a wide range of operating systems, including Windows, macOS, Linux, and many others.

    Basic Ruby Example

    fun main() {
        println("Hello, Kotlin!")
    }

    Hello World Program:

    # Define a class
    class Person
      # Constructor method
      def initialize(name, age)
        @name = name
        @age = age
      end
    
      # Method to display person details
      def display_details
        puts "Name: #{@name}, Age: #{@age}"
      end
    end
    
    # Create an object of the Person class
    person = Person.new("Alice", 30)
    person.display_details  # Output: Name: Alice, Age: 30

    Basic Control Structures:

    # If-else statement
    number = 10
    
    if number > 5
      puts "Number is greater than 5"
    else
      puts "Number is less than or equal to 5"
    end
    
    # Looping with 'each'
    [1, 2, 3, 4, 5].each do |num|
      puts num
    end

    Functions:

    # Define a function
    def greet(name)
      return "Hello, #{name}!"
    end
    
    # Call the function
    puts greet("Alice")  # Output: Hello, Alice!
  • Ruby Tutorial Roadmap

    Introduction to Ruby

    Overview of Ruby

    Ruby is a dynamic, object-oriented, and open-source programming language known for its simplicity, readability, and developer productivity. It is widely used for web development, scripting, automation, and backend development (notably with Ruby on Rails).

    Ruby Programming Language

    • History and evolution of Ruby
    • Philosophy: “Developer happiness”

    Comparison with Other Programming Languages

    • Ruby vs Java
    • Ruby vs Python
    • Ruby vs C++

    Importance of Ruby

    • Clean and expressive syntax
    • Strong object-oriented features
    • Large ecosystem and community
    • Ideal for rapid application development

    Basic Ruby Example

    • Writing and understanding a simple Ruby program

    Basic Concepts in Ruby

    Ruby Keywords

    • Reserved words and their usage

    Ruby Data Types

    • Numbers
    • Strings
    • Symbols
    • Arrays
    • Hashes
    • Booleans

    Types of Variables in Ruby

    • Local variables
    • Instance variables
    • Class variables
    • Global variables

    Global Variables

    • Usage and scope of global variables

    Literals

    • Numeric literals
    • String literals
    • Symbol literals

    Ruby Directories

    • Understanding Ruby file and directory structure

    Control Statements in Ruby

    Decision-Making Statements

    • if statement
    • if-else statement
    • if-else-if
    • Ternary operator

    Loops in Ruby

    • for loop
    • while loop
    • do..while loop
    • until loop

    Case Statement

    • Using case for conditional logic

    Control Flow Alteration

    • break and next statements
    • redo and retry statements

    File Handling in Ruby

    File Operations

    • Creating files
    • Reading files
    • Writing to files
    • Closing files

    Methods in Ruby

    Ruby Methods

    • Defining and calling methods

    Method Visibility

    • Public
    • Private
    • Protected

    Recursion in Ruby

    • Recursive method calls

    Ruby Hook Methods

    • Lifecycle hook methods

    Ruby Range Class Methods

    • Working with ranges and their methods

    Object-Oriented Programming (OOP) in Ruby

    OOP Concepts

    • Principles of object-oriented programming

    Classes and Objects

    • Creating classes and objects

    Private Classes

    • Access control in Ruby classes

    Freezing Objects

    • Preventing object modification using freeze

    Inheritance in Ruby

    • Parent and child classes

    Polymorphism

    • Method overriding and dynamic behavior

    Encapsulation

    • Data hiding using access control

    Mixins

    • Using modules as mixins

    Instance Variables

    • Defining and accessing instance variables

    Data Abstraction

    • Hiding implementation details

    Exception Handling in Ruby

    Ruby Exceptions

    • Types of exceptions

    Exception Handling

    • begin, rescue, ensure

    Catch and Throw

    • Non-local exits using catch and throw

    Exception Handling in Threads

    • Managing errors in multithreaded programs

    Exception Class

    • Exception class hierarchy and methods

    Regular Expressions in Ruby

    Ruby Regex

    • Pattern matching basics

    Search and Replace

    • Using regex for search and replace operations

    Ruby Built-in Classes

    Float Class

    • Floating-point operations

    Integer Class

    • Integer operations

    Symbol Class

    • Symbols and their use cases

    Struct Class

    • Lightweight data structures

    Ruby Modules

    Ruby Module Basics

    • Creating and using modules

    Comparable Module

    • Object comparison

    Math Module

    • Mathematical functions

    Include vs Extend

    • Differences and use cases

    Collections in Ruby

    Arrays

    • Creating and manipulating arrays

    Strings

    • String basics
    • String interpolation

    Hashes

    • Hash basics
    • Working with key-value pairs

    Multithreading in Ruby

    Introduction to Threading

    • Basics of multithreading

    Thread Lifecycle

    • Thread states and execution flow

    Miscellaneous Topics

    Iterators in Ruby

    • Types of iterators

    Getters and Setters

    • Attribute readers and writers

  • Advance Cpp

    STL (Standard Template Library)

    Multithreading is a feature in C++ that allows multiple threads to run concurrently, making better use of the CPU. Each thread is a separate flow of execution within a process, which allows multiple parts of a program to run in parallel.

    Multithreading support was added in C++11, and before that, programmers had to use the POSIX threads (pthreads) library. C++11 introduced std::thread, which made multithreading much easier and portable across different platforms. The std::thread class and related utilities are provided in the <thread> header.

    Syntax for Creating a Thread:

    std::thread thread_object(callable);

    Here, std::thread represents a single thread in C++. To start a new thread, we create a std::thread object and pass a callable to its constructor. A callable can be:

    1. A Function Pointer
    2. A Lambda Expression
    3. A Function Object (Functor)
    4. A Non-Static Member Function
    5. A Static Member Function

    Once the callable is passed, the thread will execute the corresponding code.

    Launching a Thread Using a Function Pointer

    A function pointer can be passed to a std::thread constructor to launch a thread:

    void my_function(int value)
    {
        for (int i = 0; i < value; i++) {
            std::cout << "Thread using function pointer\n";
        }
    }
    
    // Creating and launching the thread
    std::thread my_thread(my_function, 5);
    Launching a Thread Using a Lambda Expression

    A lambda expression is a convenient way to define a callable on the fly. Here’s how to use it to launch a thread:

    auto my_lambda = [](int value) {
        for (int i = 0; i < value; i++) {
            std::cout << "Thread using lambda expression\n";
        }
    };
    
    // Launching a thread using the lambda expression
    std::thread my_thread(my_lambda, 5);
    Launching a Thread Using a Function Object (Functor)

    A function object (functor) is a class with an overloaded () operator. Here’s an example:

    class Functor {
    public:
        void operator()(int value) {
            for (int i = 0; i < value; i++) {
                std::cout << "Thread using functor\n";
            }
        }
    };
    
    // Launching a thread using a function object
    std::thread my_thread(Functor(), 5);

    Output:

    a < b  : 0
    a > b  : 1
    a <= b: 0
    a >= b: 1
    a == b: 0
    a != b : 1
    Launching a Thread Using a Non-Static Member Function

    Non-static member functions require an instance of the class to be called. Here’s how to use a non-static member function in a thread:

    class MyClass {
    public:
        void my_method(int value) {
            for (int i = 0; i < value; i++) {
                std::cout << "Thread using non-static member function\n";
            }
        }
    };
    
    // Creating an instance of the class
    MyClass my_obj;
    
    // Launching the thread
    std::thread my_thread(&MyClass::my_method, &my_obj, 5);
    Launching a Thread Using a Static Member Function

    Static member functions do not require an instance of the class and can be directly passed to a thread:

    class MyClass {
    public:
        static void my_static_method(int value) {
            for (int i = 0; i < value; i++) {
                std::cout << "Thread using static member function\n";
            }
        }
    };
    
    // Launching the thread using the static member function
    std::thread my_thread(&MyClass::my_static_method, 5);
    Waiting for Threads to Finish

    Once a thread is launched, we may need to wait for it to finish before proceeding. The join() function blocks the calling thread until the specified thread completes execution.

    int main() {
        std::thread t1(my_function, 5);
        t1.join();  // Wait for t1 to finish
    
        // Proceed with other tasks after t1 finishes
    }
    Complete C++ Program for Multithreading

    Below is a complete C++ program that demonstrates launching threads using different callables, including a function pointer, lambda expression, functor, and member functions:

    #include <iostream>
    #include <thread>
    
    // Function to be used as a function pointer
    void function_pointer(int value) {
        for (int i = 0; i < value; i++) {
            std::cout << "Thread using function pointer\n";
        }
    }
    
    // Functor (Function Object)
    class Functor {
    public:
        void operator()(int value) {
            for (int i = 0; i < value; i++) {
                std::cout << "Thread using functor\n";
            }
        }
    };
    
    // Class with member functions
    class MyClass {
    public:
        void non_static_function() {
            std::cout << "Thread using non-static member function\n";
        }
        static void static_function() {
            std::cout << "Thread using static member function\n";
        }
    };
    
    int main() {
        std::cout << "Launching threads...\n";
    
        // Launch thread using function pointer
        std::thread t1(function_pointer, 3);
    
        // Launch thread using functor
        Functor functor;
        std::thread t2(functor, 3);
    
        // Launch thread using lambda expression
        auto lambda = [](int value) {
            for (int i = 0; i < value; i++) {
                std::cout << "Thread using lambda expression\n";
            }
        };
        std::thread t3(lambda, 3);
    
        // Launch thread using non-static member function
        MyClass obj;
        std::thread t4(&MyClass::non_static_function, &obj);
    
        // Launch thread using static member function
        std::thread t5(&MyClass::static_function);
    
        // Wait for all threads to finish
        t1.join();
        t2.join();
        t3.join();
        t4.join();
        t5.join();
    
        std::cout << "All threads finished.\n";
    
        return 0;
    }

    Output:

    Launching threads...
    Thread using function pointer
    Thread using function pointer
    Thread using function pointer
    Thread using lambda expression
    Thread using lambda expression
    Thread using lambda expression
    Thread using functor
    Thread using functor
    Thread using functor
    Thread using non-static member function
    Thread using static member function
    All threads finished.

    Pointers in C++

    Pointers in C++ are used to access external resources, such as heap memory. When you access an external resource without a pointer, you only interact with a copy, meaning changes to the copy won’t affect the original resource. However, when you use a pointer, you can modify the original resource directly.

    Common Issues with Normal Pointers

    1. Memory Leaks: Occur when memory is allocated but not freed, leading to wasted memory and potential program crashes.
    2. Dangling Pointers: Happen when a pointer refers to memory that has already been deallocated.
    3. Wild Pointers: Pointers that are declared but not initialized to point to a valid address.
    4. Data Inconsistency: Happens when memory data is not updated uniformly across the program.
    5. Buffer Overflow: Occurs when writing outside of allocated memory, which can corrupt data or cause security issues.

    Example of Memory Leak:

    #include <iostream>
    using namespace std;
    
    class Demo {
    private:
        int data;
    };
    
    void memoryLeak() {
        Demo* p = new Demo();
    }
    
    int main() {
        while (true) {
            memoryLeak();
        }
        return 0;
    }

    Explanation:
    In the memoryLeak function, a pointer to a dynamically created Demo object is created, but the memory allocated by new is never deallocated using delete, leading to a memory leak as the program keeps allocating memory without freeing it.

    Smart Pointers

    Smart pointers in C++ automatically manage memory allocation and deallocation, avoiding manual delete calls and preventing memory leaks. Unlike normal pointers, smart pointers automatically free the memory when they go out of scope. Smart pointers overload operators like * and -> to behave similarly to normal pointers but with additional memory management features.

    Example of a Smart Pointer:

    #include <iostream>
    using namespace std;
    
    class SmartPtr {
        int* ptr;
    public:
        explicit SmartPtr(int* p = nullptr) { ptr = p; }
        ~SmartPtr() { delete ptr; }
        int& operator*() { return *ptr; }
    };
    
    int main() {
        SmartPtr sp(new int());
        *sp = 30;
        cout << *sp << endl;  // Outputs 30
        return 0;
    }

    Explanation:
    The destructor of the SmartPtr class automatically frees the memory when the object goes out of scope, preventing memory leaks.

    Differences Between Normal Pointers and Smart Pointers
    PointerSmart Pointer
    A pointer holds a memory address and data type info.Smart pointers are objects that wrap a pointer.
    A normal pointer does not deallocate memory when it goes out of scope.Automatically deallocates memory when out of scope.
    Manual memory management is required.Handles memory management automatically.

    Generic Smart Pointer Using Templates:

    #include <iostream>
    using namespace std;
    
    template <class T>
    class SmartPtr {
        T* ptr;
    public:
        explicit SmartPtr(T* p = nullptr) { ptr = p; }
        ~SmartPtr() { delete ptr; }
        T& operator*() { return *ptr; }
        T* operator->() { return ptr; }
    };
    
    int main() {
        SmartPtr<int> sp(new int());
        *sp = 40;
        cout << *sp << endl;  // Outputs 40
        return 0;
    }
    Types of Smart Pointers

    C++ provides several types of smart pointers that are available in the standard library:

    1. unique_ptr: Manages a single object and ensures that only one unique_ptr instance can point to a particular object.
    2. shared_ptr: Allows multiple shared_ptr objects to share ownership of the same object, managing reference counting.
    3. weak_ptr: A non-owning smart pointer that is used in conjunction with shared_ptr to avoid circular references.

    Example: Using unique_ptr

    Area: 48
    Area (after transfer): 48

    Explanation:
    The ownership of the object is transferred from up1 to up2 using std::move. After the transfer, up1 becomes null, and up2 owns the object.

    Example: Using shared_ptr

    #include <iostream>
    #include <memory>
    using namespace std;
    
    class Circle {
        int radius;
    public:
        Circle(int r) : radius(r) {}
        int circumference() { return 2 * 3.14 * radius; }
    };
    
    int main() {
        shared_ptr<Circle> sp1(new Circle(7));
        cout << "Circumference: " << sp1->circumference() << endl;
    
        shared_ptr<Circle> sp2 = sp1;
        cout << "Reference count: " << sp1.use_count() << endl;
    
        return 0;
    }

    Output:

    Circumference: 43.96
    Reference count: 2

    Explanation:
    Both sp1 and sp2 share ownership of the Circle object, and the reference count is managed automatically.

    Example: Using weak_ptr

    #include <iostream>
    #include <memory>
    using namespace std;
    
    class Box {
        int size;
    public:
        Box(int s) : size(s) {}
        int getSize() { return size; }
    };
    
    int main() {
        shared_ptr<Box> sp1(new Box(15));
        weak_ptr<Box> wp1(sp1);  // weak_ptr does not increase reference count
    
        cout << "Box size: " << sp1->getSize() << endl;
        cout << "Reference count: " << sp1.use_count() << endl;
    
        return 0;
    }

    Output:

    Box size: 15
    Reference count: 1

    auto_ptr vs unique_ptr vs shared_ptr vs weak_ptr in C++

    Smart pointers in C++ are special objects that manage memory and resources automatically. They are part of the C++ Standard Library and are defined in the <memory> header. The key types of smart pointers are:

    1. auto_ptr (deprecated in C++11)
    2. unique_ptr
    3. shared_ptr
    4. weak_ptr

    These smart pointers are used to manage dynamic memory and other resources, ensuring proper cleanup and preventing issues such as memory leaks and dangling pointers.

    1. auto_ptr :auto_ptr was a smart pointer in C++ before C++11 but was deprecated because of its limitations. It manages the memory of dynamically allocated objects and automatically deletes the object when the auto_ptr goes out of scope. However, auto_ptr follows a transfer-of-ownership model, meaning only one pointer can own an object at a time. Copying or assigning an auto_ptr transfers ownership, making the original pointer empty.

    Example:

    (10 * 5) + (8 / 2) = 50 + 4 = 54

    Example 1: C Program to Calculate the Area and Perimeter of a Rectangle

    #include <iostream>
    #include <memory>
    using namespace std;
    
    class MyClass {
    public:
        void display() { cout << "MyClass::display()" << endl; }
    };
    
    int main() {
        auto_ptr<MyClass> ptr1(new MyClass);
        ptr1->display();
    
        // Transfer ownership to ptr2
        auto_ptr<MyClass> ptr2(ptr1);
        ptr2->display();
    
        // ptr1 is now empty
        cout << "ptr1: " << ptr1.get() << endl;
        cout << "ptr2: " << ptr2.get()

    Output:

    Area = 21
    Perimeter = 20

    Why is auto_ptr deprecated?

    • Ownership Transfer:When copying or assigning an auto_ptr, ownership is transferred, and the source pointer becomes null. This behavior made auto_ptr unsuitable for use in STL containers, which require copy semantics.
    • Lack of Reference Counting: auto_ptr does not support shared ownership, so it cannot be used in scenarios where multiple pointers need to reference the same object.

    2. unique_ptr:unique_ptr was introduced in C++11 to replace auto_ptr. It provides exclusive ownership of a dynamically allocated object and ensures that only one unique_ptr can manage a resource at a time. It prevents copying but supports transferring ownership using the std::move() function.

    Example:

    #include <iostream>
    #include <memory>
    using namespace std;
    
    class MyClass {
    public:
        void display() { cout << "MyClass::display()" << endl; }
    };
    
    int main() {
        unique_ptr<MyClass> ptr1(new MyClass);
        ptr1->display();
    
        // Transfer ownership to ptr2
        unique_ptr<MyClass> ptr2 = move(ptr1);
        ptr2->display();
    
        // ptr1 is now empty
        cout << "ptr1: " << ptr1.get() << endl;
        cout << "ptr2: " << ptr2.get() << endl;
    
        return 0;
    }

    Output:

    MyClass::display()
    MyClass::display()
    ptr1: 0
    ptr2: <address>
    Key Features of unique_ptr:
    • Exclusive Ownership: Only one unique_ptr can own a resource at a time.
    • Move Semantics: Ownership can be transferred using std::move().
    • Resource Management: When the unique_ptr goes out of scope, the resource is automatically freed.

    3. shared_ptr :shared_ptr provides shared ownership of a dynamically allocated object. It uses a reference counting mechanism to keep track of how many pointers are pointing to the object. The object is only destroyed when the reference count reaches zero, meaning all shared_ptrs referencing the object have been deleted.

    Example:

    #include <iostream>
    #include <memory>
    using namespace std;
    
    class MyClass {
    public:
        void display() { cout << "MyClass::display()" << endl; }
    };
    
    int main() {
        shared_ptr<MyClass> ptr1(new MyClass);
        ptr1->display();
    
        // Share ownership with ptr2
        shared_ptr<MyClass> ptr2(ptr1);
        cout << "ptr1 count: " << ptr1.use_count() << endl;
        cout << "ptr2 count: " << ptr2.use_count() << endl;
    
        // Reset ptr1
        ptr1.reset();
        cout << "ptr1: " << ptr1.get() << endl;
        cout << "ptr2 count after ptr1 reset: " << ptr2.use_count() << endl;
    
        return 0;
    }

    Output:

    MyClass::display()
    ptr1 count: 2
    ptr2 count: 2
    ptr1: 0
    ptr2 count after ptr1 reset: 1

    this Pointer in C++

    In C++, the this pointer refers to the current object of a class and is implicitly passed to all non-static member function calls. It is a hidden argument that provides access to the calling object inside the member function.

    Type of this Pointer

    The type of the this pointer depends on whether the member function is constvolatile, or both. The this pointer type will either be const ExampleClass* or ExampleClass* based on whether the member function is const or not.

    1) Const ExampleClassWhen a member function is declared as const, the type of the this pointer inside that function becomes const ExampleClass* const. This ensures that the function cannot modify the object that called it.

    Example:

    #include <iostream>
    using namespace std;
    
    class Demo {
    public:
        void show() const {
            // 'this' is implicitly passed as a hidden argument
            // The type of 'this' is 'const Demo* const'
            cout << "Const member function called" << endl;
        }
    };
    
    int main() {
        Demo obj;
        obj.show();
        return 0;
    }

    2) Non-Const ExampleClassIf the member function is not const, the this pointer is of type ExampleClass* const. This means that the function can modify the state of the object it is called on.

    Example:

    #include <iostream>
    using namespace std;
    
    class Demo {
    public:
        void show() {
            // 'this' is implicitly passed as a hidden argument
            // The type of 'this' is 'Demo* const'
            cout << "Non-const member function called" << endl;
        }
    };
    
    int main() {
        Demo obj;
        obj.show();
        return 0;
    }

    3) Volatile ExampleClassWhen a member function is declared as volatile, the type of the this pointer becomes volatile ExampleClass* const. This means that the function can work with objects that are volatile (i.e., objects that can be modified outside the program’s control).

    Example:

    #include <iostream>
    using namespace std;
    
    class Demo {
    public:
        void show() volatile {
            // 'this' is implicitly passed as a hidden argument
            // The type of 'this' is 'volatile Demo* const'
            cout << "Volatile member function called" << endl;
        }
    };
    
    int main() {
        volatile Demo obj;
        obj.show();
        return 0;
    }

    4) Const Volatile ExampleClassIf a member function is declared as both const and volatile, the type of the this pointer becomes const volatile ExampleClass* const.

    Example:

    #include <iostream>
    using namespace std;
    
    class Demo {
    public:
        void show() const volatile {
            // 'this' is implicitly passed as a hidden argument
            // The type of 'this' is 'const volatile Demo* const'
            cout << "Const volatile member function called" << endl;
        }
    };
    
    int main() {
        const volatile Demo obj;
        obj.show();
        return 0;
    }

    “delete this” in C++

    Using delete this in C++

    The delete operator should ideally not be used on the this pointer, as it can lead to undefined behavior if not handled carefully. However, if it is used, the following considerations must be taken into account:

    1) The object must be created using newThe delete operator only works for objects that have been dynamically allocated using the new operator. If an object is created on the stack or as a local variable (i.e., without new), using delete this will result in undefined behavior.

    Example:

    #include <iostream>
    using namespace std;
    
    class MyClass {
    public:
        void destroy() {
            delete this;  // Deletes the current object
        }
    };
    
    int main() {
        // Valid: Object created using new
        MyClass* obj = new MyClass;
        obj->destroy();
        obj = nullptr;  // Ensure pointer is set to null after deletion
    
        // Invalid: Undefined behavior, object created on the stack
        MyClass obj2;
        obj2.destroy();  // This will cause undefined behavior
    
        return 0;
    }

    In the valid case, the object is dynamically allocated, and using delete this will correctly free the memory. In the invalid case, the object is created locally, and deleting a non-dynamic object leads to undefined behavior.

    2) Accessing members after delete this leads to undefined behavior : Once delete this is called, the object is destroyed, and any attempt to access its members after deletion results in undefined behavior. The program might appear to work, but accessing members of a deleted object is dangerous and unreliable.

    Example:

    #include <iostream>
    using namespace std;
    
    class MyClass {
        int value;
    public:
        MyClass() : value(42) {}
    
        void destroy() {
            delete this;
    
            // Invalid: Undefined behavior
            cout << value << endl;  // This might work but is unsafe
        }
    };
    
    int main() {
        MyClass* obj = new MyClass;
        obj->destroy();  // Calls delete this and tries to access a deleted object
        return 0;
    }

    Output:

    42  // This is unpredictable and could vary depending on the system

    Passing a Function as a Parameter in C++

    In C++, functions can be passed as parameters in various ways. This technique is useful, for instance, when passing custom comparator functions in algorithms like std::sort(). There are three primary ways to pass a function as an argument:

    1. Passing a function pointer
    2. Using std::function<>
    3. Using lambdas

    1. Passing a Function Pointer : A function can be passed to another function by passing its address, which can be done through a pointer.

    Example:

    #include <iostream>
    using namespace std;
    
    // Function to add two numbers
    int add(int x, int y) { return x + y; }
    
    // Function to multiply two numbers
    int multiply(int x, int y) { return x * y; }
    
    // Function that takes a pointer to another function
    int execute(int x, int y, int (*func)(int, int)) {
        return func(x, y);
    }
    
    int main() {
        // Pass pointers to the 'add' and 'multiply' functions
        cout << "Addition of 15 and 5: " << execute(15, 5, &add) << '\n';
        cout << "Multiplication of 15 and 5: " << execute(15, 5, &multiply) << '\n';
    
        return 0;
    }

    Output:

    Addition of 15 and 5: 20
    Multiplication of 15 and 5: 75

    2. Using std::function<> : From C++11, the std::function<> template class allows passing functions as objects. A std::function<> object can be created using the following format:

    std::function<return_type(arg1_type, arg2_type...)> obj_name;

    You can then call the function object like this:

    return_type result = obj_name(arg1, arg2);

    Example:

    #include <functional>
    #include <iostream>
    using namespace std;
    
    // Define add and multiply functions
    int add(int x, int y) { return x + y; }
    int multiply(int x, int y) { return x * y; }
    
    // Function that accepts an object of type std::function<>
    int execute(int x, int y, function<int(int, int)> func) {
        return func(x, y);
    }
    
    int main() {
        // Pass the function as a parameter using its name
        cout << "Addition of 15 and 5: " << execute(15, 5, add) << '\n';
        cout << "Multiplication of 15 and 5: " << execute(15, 5, multiply) << '\n';
    
        return 0;
    }

    Output:

    Addition of 15 and 5: 20
    Multiplication of 15 and 5: 75

    3. Using Lambdas : Lambdas in C++ provide a way to create anonymous function objects in place. This is particularly useful when you need a function for a specific task and don’t want to define it elsewhere.

    Example:

    #include <functional>
    #include <iostream>
    using namespace std;
    
    // Function that accepts a lambda as a parameter
    int execute(int x, int y, function<int(int, int)> func) {
        return func(x, y);
    }
    
    int main() {
        // Lambda for addition
        int result1 = execute(15, 5, [](int x, int y) { return x + y; });
        cout << "Addition of 15 and 5: " << result1 << '\n';
    
        // Lambda for multiplication
        int result2 = execute(15, 5, [](int x, int y) { return x * y; });
        cout << "Multiplication of 15 and 5: " << result2 << '\n';
    
        return 0;
    }

    Output:

    Addition of 15 and 5: 20
    Multiplication of 15 and 5: 75

    Signals in C++

    Signals are interrupts that prompt an operating system (OS) to halt its current task and give attention to the task that triggered the interrupt. These signals can pause or interrupt processes running on the OS. Similarly, C++ provides several signals that can be caught and handled within a program. Below is a list of common signals and their associated operations in C++.

    SignalOperation
    SIGINTProduces a receipt for an active signal
    SIGTERMSends a termination request to the program
    SIGBUSIndicates a bus error (e.g., accessing an invalid address)
    SIGILLDetects an illegal instruction
    SIGALRMTriggered by the alarm() function when the timer expires
    SIGABRTSignals abnormal termination of a program
    SIGSTOPCannot be blocked, handled, or ignored; stops a process
    SIGSEGVIndicates invalid access to memory (segmentation fault)
    SIGFPESignals erroneous arithmetic operations like division by zero
    SIGUSR1, SIGUSR2User-defined signals

    signal() Function: The signal() function, provided by the signal library, is used to catch and handle unexpected signals or interrupts in a C++ program.

    Syntax:

    signal(registered_signal, signal_handler);
    • The first argument is an integer that represents the signal number.
    • The second argument is a pointer to the function that will handle the signal.

    The signal must be registered with a handler function before it can be caught. The handler function should have a return type of void.

    Example:

    #include <csignal>
    #include <iostream>
    using namespace std;
    
    void handle_signal(int signal_num) {
        cout << "Received interrupt signal (" << signal_num << ").\n";
        exit(signal_num);  // Terminate the program
    }
    
    int main() {
        // Register SIGABRT and set the handler
        signal(SIGABRT, handle_signal);
    
        while (true) {
            cout << "Running program..." << endl;
        }
    
        return 0;
    }

    Output:

    Running program...
    Running program...
    Running program...

    When you press Ctrl+C, which generates an interrupt signal (e.g., SIGABRT), the program will terminate and print:

    Received interrupt signal (22).

    raise() Function : The raise() function is used to generate signals in a program.

    Syntax:

    raise(signal);

    It takes a signal from the predefined list as its argument.

    Example:

    // C program to demonstrate the use of relational operators
    #include <stdio.h>
    
    int main() {
        int num1 = 12, num2 = 8;
    
        // greater than
        if (num1 > num2)
            printf("num1 is greater than num2\n");
        else
            printf("num1 is less than or equal to num2\n");
    
        // greater than or equal to
        if (num1 >= num2)
            printf("num1 is greater than or equal to num2\n");
        else
            printf("num1 is less than num2\n");
    
        // less than
        if (num1 < num2)
            printf("num1 is less than num2\n");
        else
            printf("num1 is greater than or equal to num2\n");
    
        // less than or equal to
        if (num1 <= num2)
            printf("num1 is less than or equal to num2\n");
        else
            printf("num1 is greater than num2\n");
    
        // equal to
        if (num1 == num2)
            printf("num1 is equal to num2\n");
        else
            printf("num1 and num2 are not equal\n");
    
        // not equal to
        if (num1 != num2)
            printf("num1 is not equal to num2\n");
        else
            printf("num1 is equal to num2\n");
    
        return 0;
    }

    Output:

    Running program...
    Running program...
    Running program...
    Caught signal (11).

  • Namespaces

    Introduction to Namespaces in C++

    A namespace in C++ provides a context where you can declare identifiers such as variables, methods, and classes. It helps in organizing code and avoiding name collisions. For instance, if your code has a function named xyz() and a library also has a function with the same name, the compiler will not be able to distinguish between the two without namespaces. A namespace helps resolve this issue by adding context to the function, class, or variable name.

    A namespace essentially defines a scope, and one of its major benefits is preventing name collisions. A well-known example is the std namespace in the C++ Standard Library, where various classes, methods, and templates are defined. While coding in C++, we commonly use using namespace std; to access these elements without needing to prefix std:: to each function call or variable access.

    Defining a Namespace

    To declare a namespace, use the namespace keyword followed by the namespace name:

    namespace my_namespace {
        int variable;
        void function();
        class MyClass {};
    }

    No semicolon is needed after the closing brace of a namespace definition. To access elements within the namespace, use the following syntax:

    my_namespace::variable;
    my_namespace::function();
    Using the using Directive

    The using directive allows you to avoid specifying the namespace every time you use a variable or function. By writing using namespace my_namespace;, you tell the compiler that all identifiers in the code are from the given namespace.

    #include <iostream>
    using namespace std;
    
    namespace first_space {
        void func() {
            cout << "Inside first_space" << endl;
        }
    }
    
    namespace second_space {
        void func() {
            cout << "Inside second_space" << endl;
        }
    }
    
    using namespace first_space;
    
    int main() {
        func();  // This calls the function from first_space
        return 0;
    }

    Output:

    Inside first_space

    The using directive applies from the point where it’s used until the end of the scope. If another entity with the same name exists in a broader scope, it gets hidden.

    Nested Namespaces

    Namespaces can also be nested, where one namespace is defined within another. For example:

    namespace outer {
        namespace inner {
            void func() {
                std::cout << "Inside inner namespace" << std::endl;
            }
        }
    }

    Output:

    Inside second_space
    Scope of Entities in a Namespace

    Entities, such as variables and functions, defined in a namespace are scoped within that namespace. This means you can have entities with the same name in different namespaces without causing errors.

    #include <iostream>
    using namespace std;
    
    namespace first_space {
        void func() {
            cout << "Inside first_space" << endl;
        }
    }
    
    namespace second_space {
        void func() {
            cout << "Inside second_space" << endl;
        }
    }
    
    int main() {
        first_space::func();  // Calls function from first_space
        second_space::func();  // Calls function from second_space
        return 0;
    }

    Output:

    Inside first_space
    Inside second_space
    Namespaces in Practice

    Consider the following code that demonstrates the error caused by using two variables with the same name in the same scope:

    int main() {
        int value;
        value = 0;
        double value;  // Error: redeclaration of 'value'
        value = 0.0;
    }

    Error:

    Compiler Error: 'value' has a previous declaration as 'int value'

    With namespaces, you can declare two variables with the same name in different namespaces without conflict:

    #include <iostream>
    using namespace std;
    
    namespace first_space {
        int val = 500;
    }
    
    int val = 100;
    
    int main() {
        int val = 200;
        cout << first_space::val << endl;
        return 0;
    }

    Output:

    ns::Geek::display()

    Alternatively, a class can be declared inside a namespace and defined outside the namespace:

    #include <iostream>
    using namespace std;
    
    namespace ns {
        class Geek;
    }
    
    class ns::Geek {
    public:
        void display() {
            cout << "ns::Geek::display()" << endl;
        }
    };
    
    int main() {
        ns::Geek obj;
        obj.display();
        return 0;
    }

    Output:

    ns::Geek::display()

    Namespaces in C++ (Set 2: Extending and Unnamed Namespaces)

    Defining a Namespace:

    A namespace definition in C++ starts with the namespace keyword followed by the name of the namespace, like so:

    namespace my_namespace
    {
        // Variable declarations
        int my_var;
    
        // Method declarations
        void my_function();
    
        // Class declarations
        class MyClass {};
    }

    Note that there is no semicolon after the closing brace of the namespace definition. To use variables or functions from a specific namespace, prepend the namespace name with the scope resolution operator (::), like this:

    my_namespace::my_var;
    my_namespace::my_function();
    The using Directive:

    To avoid manually prepending the namespace name each time, you can use the using namespace directive. This tells the compiler to implicitly use the names from the specified namespace:

    #include <iostream>
    using namespace std;
    
    // Define namespaces
    namespace first_space
    {
        void func()
        {
            cout << "Inside first_space" << endl;
        }
    }
    
    namespace second_space
    {
        void func()
        {
            cout << "Inside second_space" << endl;
        }
    }
    
    using namespace first_space;
    
    int main()
    {
        func();  // Calls the function from first_space
        return 0;
    }

    The names introduced by the using directive follow normal scoping rules. Once introduced, they are visible from the point of the directive to the end of the scope where it was used.

    Nested Namespaces:

    You can also define namespaces within other namespaces, referred to as nested namespaces:

    namespace outer_space
    {
        namespace inner_space
        {
            void func()
            {
                // Function inside inner_space
            }
        }
    }

    To access members of a nested namespace, use the following syntax:

    using namespace outer_space::inner_space;

    If you only use outer_space, it will also make the inner namespace available in scope:

    #include <iostream>
    using namespace std;
    
    namespace outer_space
    {
        void outer_func()
        {
            cout << "Inside outer_space" << endl;
        }
    
        namespace inner_space
        {
            void inner_func()
            {
                cout << "Inside inner_space" << endl;
            }
        }
    }
    
    using namespace outer_space::inner_space;
    
    int main()
    {
        inner_func();  // Calls function from inner_space
        return 0;
    }
    Creating Multiple Namespaces:

    It’s possible to create multiple namespaces with different names in the global scope. Here’s an example:

    #include <iostream>
    using namespace std;
    
    // First namespace
    namespace first
    {
        int func() { return 5; }
    }
    
    // Second namespace
    namespace second
    {
        int func() { return 10; }
    }
    
    int main()
    {
        cout << first::func() << endl;   // Calls func() from first namespace
        cout << second::func() << endl;  // Calls func() from second namespace
        return 0;
    }

    Output:

    5
    10
    Extending Namespaces:

    It is possible to define a namespace in parts using the same name more than once. Essentially, the second block is an extension of the first:

    #include <iostream>
    using namespace std;
    
    namespace first
    {
        int val1 = 500;
    }
    
    namespace first
    {
        int val2 = 501;
    }
    
    int main()
    {
        cout << first::val1 << endl;  // Accesses first part of the namespace
        cout << first::val2 << endl;  // Accesses second part of the namespace
        return 0;
    }

    Output:

    500
    501
    Unnamed Namespaces:

    Unnamed namespaces allow you to define identifiers that are unique to the file they are declared in. They can be seen as a replacement for the old static keyword for file-scope variables. In unnamed namespaces, no namespace name is provided, and the compiler generates a unique name for it:

    #include <iostream>
    using namespace std;
    
    namespace
    {
        int rel = 300;
    }
    
    int main()
    {
        cout << rel << endl;  // Prints 300
        return 0;
    }

    Output:

    300

    Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing)

    Different Ways to Access Namespaces in C++

    In C++, there are multiple ways to access variables and functions within a namespace. Here’s an explanation with modified examples.

    Defining a Namespace

    A namespace definition starts with the namespace keyword followed by the name of the namespace, as shown below:

    namespace my_namespace
    {
        // Variable declaration
        int my_var;
    
        // Function declaration
        void my_function();
    
        // Class declaration
        class MyClass {};
    }

    There is no semicolon after the closing brace. To access variables or functions from the namespace, use the following syntax:

    my_namespace::my_var;     // Access variable
    my_namespace::my_function();  // Access function
    The using Directive

    To avoid repeatedly writing the namespace name, you can use the using namespace directive. This informs the compiler to assume that all names used after the directive come from the specified namespace:

    #include <iostream>
    using namespace std;
    
    // First namespace
    namespace first_ns
    {
        void display()
        {
            cout << "Inside first_ns" << endl;
        }
    }
    
    // Second namespace
    namespace second_ns
    {
        void display()
        {
            cout << "Inside second_ns" << endl;
        }
    }
    
    using namespace first_ns;
    
    int main()
    {
        display();  // Calls the function from first_ns
        return 0;
    }

    In this case, the function from first_ns will be called because of the using directive.

    Nested Namespaces

    Namespaces can be nested, meaning you can define one namespace inside another:

    namespace outer_ns
    {
        void outer_function() {}
    
        namespace inner_ns
        {
            void inner_function() {}
        }
    }

    You can access members of a nested namespace using the following syntax:

    using namespace outer_ns::inner_ns;

    Alternatively, you can also use a more hierarchical approach:

    #include <iostream>
    using namespace std;
    
    // Outer namespace
    namespace outer_ns
    {
        void outer_function()
        {
            cout << "Inside outer_ns" << endl;
        }
    
        // Inner namespace
        namespace inner_ns
        {
            void inner_function()
            {
                cout << "Inside inner_ns" << endl;
            }
        }
    }
    
    using namespace outer_ns::inner_ns;
    
    int main()
    {
        inner_function();  // Calls the function from inner_ns
        return 0;
    }
    Accessing Namespace Members

    1. Accessing Normally : You can access members of a namespace using the scope resolution operator (::)

    #include <iostream>
    using namespace std;
    
    namespace sample_ns
    {
        int number = 100;
    }
    
    int main()
    {
        cout << sample_ns::number << endl;  // Accesses variable with scope resolution
        return 0;
    }

    Output:

    100

    2. Using the using Directive : You can also use the using directive to make variables and functions directly accessible:

    #include <iostream>
    using namespace std;
    
    namespace sample_ns
    {
        int number = 100;
    }
    
    // Use of 'using' directive
    using namespace sample_ns;
    
    int main()
    {
        cout << number << endl;  // Accesses variable without scope resolution
        return 0;
    }

    Example:

    100
    Using Namespaces Across Files

    Namespaces can be defined in one file and accessed from another. This can be done as follows:

    File 1 (header file):

    // file1.h
    namespace sample_ns
    {
        int getValue()
        {
            return 50;
        }
    }

    File 2 (source file):

    // file2.cpp
    #include <iostream>
    #include "file1.h"  // Including file1.h
    using namespace std;
    
    int main()
    {
        cout << sample_ns::getValue();  // Accessing function from file1.h
        return 0;
    }

    This allows the function declared in file1.h to be used in file2.cpp.

    Nested Namespaces

    In C++, namespaces can also be nested, meaning one namespace can be declared inside another:

    #include <iostream>
    using namespace std;
    
    // Outer namespace
    namespace outer_ns
    {
        int value = 10;
        namespace inner_ns
        {
            int inner_value = value;  // Access outer_ns::value
        }
    }
    
    int main()
    {
        cout << outer_ns::inner_ns::inner_value << endl;  // Outputs 10
        return 0;
    }

    Output:

    10
    Namespace Aliasing

    You can create an alias for a namespace to simplify its usage. The syntax for aliasing is as follows:

    #include <iostream>
    
    namespace long_name_space
    {
        namespace nested_space
        {
            namespace deep_space
            {
                int data = 99;
            }
        }
    }
    
    // Alias for nested namespaces
    namespace short_name = long_name_space::nested_space::deep_space;
    
    int main()
    {
        std::cout << short_name::data << std::endl;  // Access data using alias
        return 0;
    }

    Output:

    99
  • Templates

    Introduction to Templates in C++

    Templates are a powerful feature in C++ that allow for generic programming. The concept behind templates is to enable functions or classes to work with any data type without rewriting code for each type. For example, a software developer may need to create a sorting function that works for various data types like integers, floating-point numbers, or characters. Instead of writing separate functions for each data type, a template can be used to write one generic function.

    C++ introduces two keywords for working with templates: template and typename. The keyword typename can also be replaced with class for convenience.

    How Templates Work

    Templates are processed at compile time, which makes them similar to macros. However, unlike macros, templates undergo type-checking during compilation. This ensures that the code is syntactically correct for the specific data type. While the source code contains a single version of the function or class, the compiler generates multiple instances for different data types.

    Function Templates

    Function templates allow for the creation of generic functions that can operate on different data types. Some commonly used function templates include sort()max()min(), and printArray().

    Here’s an example demonstrating a function template:

    // C++ Program to demonstrate the use of templates
    #include <iostream>
    using namespace std;
    
    // A function template that works for any data type
    template <typename T> T getMax(T a, T b) {
        return (a > b) ? a : b;
    }
    
    int main() {
        // Calling getMax for different data types
        cout << getMax<int>(5, 10) << endl;         // int
        cout << getMax<double>(4.5, 2.3) << endl;   // double
        cout << getMax<char>('a', 'z') << endl;     // char
    
        return 0;
    }

    Output:

    1.1 2.2 3.3 4.4 5.5
    Multiple Template Parameters

    It is possible to pass more than one type of argument to templates. This is particularly useful when you need a class or function to work with multiple types of data.

    // C++ Program to demonstrate multiple template parameters
    #include <iostream>
    using namespace std;
    
    template <class T1, class T2> class Pair {
        T1 first;
        T2 second;
    
    public:
        Pair(T1 x, T2 y) : first(x), second(y) {
            cout << "Pair initialized" << endl;
        }
    
        void display() {
            cout << "First: " << first << ", Second: " << second << endl;
        }
    };
    
    int main() {
        Pair<int, double> p1(10, 3.14);
        p1.display();
    
        Pair<string, char> p2("Hello", 'A');
        p2.display();
    
        return 0;
    }

    Output:

    Pair initialized
    First: 10, Second: 3.14
    Pair initialized
    First: Hello, Second: A
    Default Template Parameters

    Just like regular function parameters, templates can also have default arguments. This allows for flexibility in specifying the template arguments.

    // C++ Program to demonstrate default template parameters
    #include <iostream>
    using namespace std;
    
    template <class T1, class T2 = int> class MyClass {
    public:
        T1 data1;
        T2 data2;
    
        MyClass(T1 x, T2 y = 0) : data1(x), data2(y) {
            cout << "Constructor called" << endl;
        }
    
        void show() {
            cout << "Data1: " << data1 << ", Data2: " << data2 << endl;
        }
    };
    
    int main() {
        MyClass<double> obj1(4.5);
        obj1.show();
    
        MyClass<int, char> obj2(100, 'A');
        obj2.show();
    
        return 0;
    }

    Output:

    Constructor called
    Data1: 4.5, Data2: 0
    Constructor called
    Data1: 100, Data2: A

    Templates in C++: An Overview

    Templates in C++ are a powerful feature that enables us to write generic code that can work with any data type, including user-defined types. This avoids the need to write and maintain multiple versions of functions or classes for different data types. For instance, a generic sort() function can be created to sort arrays of any type. Similarly, a class like Stack can be implemented to handle various types.

    Template Specialization: Customizing Code for Specific Data Types

    Sometimes, we may need different behavior for specific data types within a template. For example, in a large project, we might use Quick Sort for most data types, but for char, we could opt for a more efficient counting sort due to the limited range of possible values (256). C++ allows us to define a special version of a template for a particular data type, a feature known as template specialization.

    Function Overloading: The Traditional Approach

    Function overloading allows us to define multiple functions with the same name but different parameter types. Here’s an example of overloaded functions:

    #include <iostream>
    using namespace std;
    
    void show(int, int);
    void show(double, double);
    void show(char, char);
    
    int main() {
        show(2, 5);
        show(2.6, 7.6);
        return 0;
    }
    
    void show(int a, int b) {
        cout << "a = " << a << endl;
        cout << "b = " << b << endl;
    }
    
    void show(double a, double b) {
        cout << "a = " << a << endl;
        cout << "b = " << b << endl;
    }

    Output:

    a = 2
    b = 5
    a = 2.6
    b = 7.6

    While function overloading works, it results in repeated code for different data types that perform the same task. This redundancy can be avoided using function templates.

    Function Templates: Eliminating Code Duplication

    function template allows us to write a generic function that works for any data type. This reduces code duplication and simplifies maintenance.

    Example of a generic sort function:

    // Generic sort function using templates
    template <class T>
    void sort(T arr[], int size) {
        // Implement Quick Sort for all data types
    }
    
    // Template specialization for char data type
    template <>
    void sort<char>(char arr[], int size) {
        // Implement Counting Sort for char
    }

    Output:

    a = 3
    b = 8
    a = 2.3
    b = 4.6

    Function Template Example: Printing the Maximum of Two Values

    #include <iostream>
    using namespace std;
    
    template <class T>
    void getMax(T a, T b) {
        T result = (a > b) ? a : b;
        cout << "Maximum: " << result << endl;
    }
    
    int main() {
        getMax(5, 10);
        getMax(7.1, 3.9);
        getMax('A', 'Z');
        return 0;
    }

    Output:

    Maximum: 10
    Maximum: 7.1
    Maximum: Z
    Template Specialization: Customizing Function Templates

    Template specialization allows us to define a specific behavior for a particular data type.

    Example of template specialization for int type:

    #include <iostream>
    using namespace std;
    
    template <class T>
    void fun(T a) {
        cout << "Generic template: " << a << endl;
    }
    
    // Specialized version for int
    template <>
    void fun(int a) {
        cout << "Specialized template for int: " << a << endl;
    }
    
    int main() {
        fun(5.6);   // Calls the generic template
        fun(10);    // Calls the specialized template for int
        return 0;
    }

    Output:

    Generic template: 5.6
    Specialized template for int: 10
    Class Templates: Creating Generic Classes

    Like functions, we can also create class templates that are independent of data types. This is useful for generic data structures such as arrays, linked lists, and stacks.

    Example of a class template:

    #include <iostream>
    using namespace std;
    
    template <class T>
    class Test {
    public:
        Test() {
            cout << "General template object\n";
        }
    };
    
    // Specialized version for int
    template <>
    class Test<int> {
    public:
        Test() {
            cout << "Specialized template for int\n";
        }
    };
    
    int main() {
        Test<int> obj1;    // Calls specialized template
        Test<double> obj2; // Calls general template
        return 0;
    }

    Output:

    Specialized template for int
    General template object

    Using Keyword in C++ STL

    The using keyword in C++ provides a convenient way to specify which namespace, class, or function to use within a scope. This becomes particularly useful when working with large libraries or codebases that involve multiple namespaces. It helps avoid repeated typing of namespace prefixes and simplifies the code.

    However, caution is required when using the using keyword, as it can potentially introduce naming conflicts, especially in large projects. Therefore, it’s best to apply it selectively to maintain clear and organized code.

    Uses of the using Keyword in C++ STL

    The using keyword can be utilized in several ways:

    1. Using for Namespaces
    2. Using for Inheritance
    3. Using for Aliasing
    4. Using for Directives

    1. Using for Namespaces : The using keyword allows you to access entities in a particular namespace without having to specify the full namespace name repeatedly.

    Example:

    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello from C++!" << endl;
        return 0;
    }

    Output:

    Value of a: 25

    2. Using for Inheritance : In C++, the using keyword can also be used to inherit constructors from a base class into a derived class. This can save time by avoiding the need to redefine constructors in the derived class.

    Example:

    #include <iostream>
    using namespace std;
    
    class Parent {
    public:
        int a;
    
        Parent(int x) : a(x) {}
    };
    
    class Child : public Parent {
    public:
        using Parent::Parent;  // Inheriting Parent's constructor
    };
    
    int main() {
        Child obj(25);
        cout << "Value of a: " << obj.a << endl;
        return 0;
    }

    Output:

    Number: 1234567890

    3. Using for Aliasing : The using keyword in C++ can be used to create type aliases, which allow developers to define alternative names for existing types. This improves code readability and makes complex type declarations easier to manage.

    Example:

    #include <iostream>
    #include <vector>
    
    using IntVector = std::vector<int>; // Alias for std::vector<int>
    
    int main() {
        IntVector numbers = {1, 2, 3, 4, 5}; // Use alias
        for (int num : numbers) {
            std::cout << num << " ";
        }
        return 0;
    }

    Output:

    1 2 3 4 5

    4. Using for Directives : The using keyword can also be used to bring specific entities from a namespace into the current scope, making the code more concise and readable.

    Example:

    #include <iostream>
    using std::cout;
    using std::endl;
    
    int main() {
        cout << "Hello, World!" << endl;
        return 0;
    }

    Output:

    Hello, World!
    Forms of the using Keyword

    1. using namespace std;: This form brings all the members of the std namespace into your code.
    2. using std::cout;: This form brings only the cout object into your code, which reduces the chances of naming conflicts.
    3. using std::endl;: Similarly, this form is used to access only the endl object.

    You can also apply the using keyword to your own custom namespaces.

    Limitations of the using Keyword

    While using can simplify code, it can also introduce problems if used carelessly:

    • Name collisions: If multiple namespaces have entities with the same name, using the using keyword indiscriminately can lead to ambiguity.
    • Global namespace: The using keyword cannot make types in the global or parent namespaces visible.
    • Static classes: It also cannot make static classes visible.

    Example:

    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Using namespace example" << endl;
        return 0;
    }

    Output:

    Using namespace example

    Example 2: Using Keyword with Selective Imports

    #include <iostream>
    using std::cout;
    using std::endl;
    
    int main() {
        cout << "Selective using example" << endl;
        return 0;
    }

    Output:

    Selective using example
  • Exception Handling

    C++ Exception Handling: A Concept Overview

    In C++, exceptions are unexpected events or errors that occur during the execution of a program. When such an event occurs, the program flow is interrupted, and if the exception is not handled, it can cause the program to terminate abnormally. Exception handling provides a way to manage these runtime anomalies and keep the program running by transferring control from one part of the code to another where the exception can be dealt with.

    What is a C++ Exception?

    An exception is a problem that arises during the execution of a program, leading to an abnormal termination if not handled. Exceptions occur at runtime, meaning the problem is only encountered when the program is running.

    Types of Exceptions in C++

    In C++, exceptions can be categorized into two types:

    1. Synchronous Exceptions: These occur due to errors like dividing by zero, invalid input, or logic errors that can be anticipated by the programmer.
    2. Asynchronous Exceptions: These are exceptions caused by external events beyond the program’s control, such as hardware failure, system interrupts, etc.

    Exception Handling Mechanism in C++

    C++ provides a built-in mechanism for exception handling through three main keywords: trycatch, and throw.

    Syntax of try-catch in C++:

    try {
        // Code that might throw an exception
        throw SomeExceptionType("Error message");
    }
    catch( ExceptionType e ) {
        // Code to handle the exception
    }

    1. Separation of Error–Handling Code from Normal Code: Unlike traditional methods where error-checking code is mixed with normal logic, exceptions keep the code cleaner and more readable.
    2. Granular Handling: A function can throw many exceptions but choose to handle only specific ones. The rest can be caught by the calling function.
    3. Grouping Error Types: C++ allows you to group exceptions into classes and objects, making it easier to categorize and manage different error types.

    Example 1: Basic try-catch Mechanism

    #include <iostream>
    #include <stdexcept>
    using namespace std;
    
    int main() {
        try {
            int numerator = 10;
            int denominator = 0;
            int result;
    
            if (denominator == 0) {
                throw runtime_error("Division by zero is not allowed.");
            }
    
            result = numerator / denominator;
            cout << "Result: " << result << endl;
        }
        catch (const exception& e) {
            cout << "Exception caught: " << e.what() << endl;
        }
    
        return 0;
    }

    Output:

    Exception caught: Division by zero is not allowed.

    In this example, dividing by zero throws a runtime_error exception, which is caught by the catch block.

    Example 2: Throwing and Catching Exceptions

    #include <iostream>
    using namespace std;
    
    int main() {
        int value = -1;
    
        cout << "Before try block" << endl;
    
        try {
            cout << "Inside try block" << endl;
            if (value < 0) {
                throw value;
            }
            cout << "After throw (will not be executed)" << endl;
        }
        catch (int ex) {
            cout << "Caught an exception: " << ex << endl;
        }
    
        cout << "After catch block" << endl;
        return 0;
    }

    Output:

    Before try block
    Inside try block
    Caught an exception: -1
    After catch block

    Here, a negative value throws an exception, and control transfers to the catch block, where the exception is handled.

    Properties of Exception Handling in C++

    Property 1: Catch-All Block : –C++ provides a catch-all mechanism to catch exceptions of any type using catch(...).

    #include <iostream>
    using namespace std;
    
    int main() {
        try {
            throw 10; // Throwing an integer
        }
        catch (char*) {
            cout << "Caught a char exception." << endl;
        }
        catch (...) {
            cout << "Caught a default exception." << endl;
        }
        return 0;
    }

    Output:

    Caught a default exception.

    Property 2: Uncaught Exceptions Terminate the Program :- If an exception is not caught anywhere in the code, the program terminates abnormally.

    #include <iostream>
    using namespace std;
    
    int main() {
        try {
            throw 'x'; // Throwing a char
        }
        catch (int) {
            cout << "Caught int" << endl;
        }
        return 0;
    }

    Output:

    terminate called after throwing an instance of 'char'

    Property 3: Unchecked Exceptions :- C++ does not enforce checking for exceptions at compile time. However, it is recommended to list possible exceptions.

    #include <iostream>
    using namespace std;
    
    void myFunction(int* ptr, int x) throw(int*, int) {
        if (ptr == nullptr) throw ptr;
        if (x == 0) throw x;
    }
    
    int main() {
        try {
            myFunction(nullptr, 0);
        }
        catch (...) {
            cout << "Caught exception from myFunction" << endl;
        }
        return 0;
    }

    Output:

    Caught exception from myFunction

    Exception Handling in C++

    Exception handling is a technique used to manage runtime anomalies or abnormal conditions that a program may encounter during its execution. These anomalies can be categorized into two types:

    1. Synchronous Exceptions: These occur due to issues in the program’s input or logic, such as division by zero.
    2. Asynchronous Exceptions: These are beyond the program’s control, such as hardware failures like a disk crash.

    In C++, the exception handling mechanism uses three primary keywords:

    • try: Defines a block of code where exceptions can occur.
    • catch: Handles exceptions that were thrown within the corresponding try block.
    • throw: Used to throw an exception when a problem arises. It can also be used to declare exceptions that a function may throw but not handle itself.
    Problem Statement

    You need to create a class named Numbers with two data members, a and b. This class should have methods to:

    • Find the greatest common divisor (GCD) of the two numbers using an iterative approach.
    • Check if a number is prime and throw a custom exception if the number is prime.

    Define a custom exception class MyPrimeException to handle cases where a number is found to be prime.

    Solution Approach

    1. Define a class Number with two private data members, a and b. Include two member functions:

    • gcd(): Computes the greatest common divisor
    • (GCD) using an iterative algorithm.
      isPrime(int n): Checks whether a number is prime.

    2. Use a constructor to initialize the two data members.
    3. Create another class, MyPrimeException, which will be invoked when a number is identified as prime, and an exception is thrown.

    #include <iostream>
    using namespace std;
    
    // Class declaration
    class Number {
    private:
        int a, b;
    
    public:
        // Constructor
        Number(int x, int y) : a(x), b(y) {}
    
        // Function to calculate the GCD of two numbers
        int gcd() {
            int num1 = a;
            int num2 = b;
    
            // Continue until both numbers are equal
            while (num1 != num2) {
                if (num1 > num2)
                    num1 = num1 - num2;
                else
                    num2 = num2 - num1;
            }
    
            return num1;
        }
    
        // Function to check if the given number is prime
        bool isPrime(int n) {
            if (n <= 1)
                return false;
    
            for (int i = 2; i * i <= n; i++) {
                if (n % i == 0)
                    return false;
            }
    
            return true;
        }
    };
    
    // Custom exception class
    class MyPrimeException {
    public:
        void displayMessage() {
            cout << "Prime number detected. Exception thrown." << endl;
        }
    };
    
    int main() {
        int x = 13, y = 56;
        Number num1(x, y);
    
        // Display the GCD of the two numbers
        cout << "GCD of " << x << " and " << y << " is = " << num1.gcd() << endl;
    
        // Prime check and exception handling
        try {
            if (num1.isPrime(x)) {
                throw MyPrimeException();
            }
            cout << x << " is not a prime number." << endl;
        }
        catch (MyPrimeException& ex) {
            ex.displayMessage();
        }
    
        try {
            if (num1.isPrime(y)) {
                throw MyPrimeException();
            }
            cout << y << " is not a prime number." << endl;
        }
        catch (MyPrimeException& ex) {
            ex.displayMessage();
        }
    
        return 0;
    }

    Output:

    GCD of 13 and 56 is = 1
    Prime number detected. Exception thrown.
    56 is not a prime number.
    Explanation:

    1. Class Number: This class encapsulates two private data members, a and b. It has:

    • A constructor that initializes these members.
    • A method gcd() that computes the GCD of the two numbers using an iterative algorithm.
    • A method isPrime(int n) that checks whether a number is prime by dividing it by every integer from 2 up to the square root of the number.

    2. Class MyPrimeException: This class is a simple custom exception class used to handle prime number cases.
    3. Main Function:

    • The gcd() method is used to calculate and display the GCD of the two numbers.
    • If either number is prime, a
    • MyPrimeException is thrown, which is caught and handled by printing a custom message.

    Stack Unwinding in C++

    Stack unwinding refers to the process of cleaning up the function call stack when an exception is thrown. This involves removing function entries from the call stack at runtime and destroying local objects in the reverse order in which they were created. In C++, when an exception occurs, the runtime system searches the function call stack for an appropriate exception handler. If no handler is found in the current function, it continues searching the previous functions in the call stack until an appropriate handler is found. Stack unwinding occurs when the functions without handlers are removed from the stack, and destructors for local objects are called.

    The concept of stack unwinding is closely tied to exception handling in C++. If an exception is thrown and not caught in the same function, the destructors for all automatic objects created since entering that function are invoked before moving to the next function in the call stack. This process continues until the exception is caught or the program terminates.

    Example

    Here’s a modified version of the code to demonstrate stack unwinding:

    #include <iostream>
    using namespace std;
    
    // Sample class with a constructor and destructor
    class Sample {
    public:
        Sample(const string& name) : objName(name) {
            cout << objName << " created." << endl;
        }
    
        ~Sample() {
            cout << objName << " destroyed." << endl;
        }
    
    private:
        string objName;
    };
    
    // Function that throws an exception
    void func1() throw(int) {
        Sample obj1("Object in func1");
        cout << "func1() Start" << endl;
        throw 404;
        cout << "func1() End" << endl;  // This line will never execute
    }
    
    // Function that calls func1
    void func2() throw(int) {
        Sample obj2("Object in func2");
        cout << "func2() Start" << endl;
        func1();
        cout << "func2() End" << endl;  // This line will never execute
    }
    
    // Function that calls func2 and catches the exception
    void func3() {
        Sample obj3("Object in func3");
        cout << "func3() Start" << endl;
        try {
            func2();
        }
        catch (int e) {
            cout << "Caught Exception: " << e << endl;
        }
        cout << "func3() End" << endl;
    }
    
    // Driver code
    int main() {
        func3();
        return 0;
    }

    Output:

    Object in func3 created.
    func3() Start
    Object in func2 created.
    func2() Start
    Object in func1 created.
    func1() Start
    Object in func1 destroyed.
    Object in func2 destroyed.
    Caught Exception: 404
    func3() End
    Object in func3 destroyed.

    Explanation:

    1. func1 throws an exception (404), which causes the control to leave the function.

    • Before exiting, the local object obj1 in func1 is destroyed as part of stack unwinding.

    2. func2 calls func1, but since func1 throws an exception and func2 does not handle it, the control leaves func2 as well.

    • The local object obj2 in func2 is destroyed before func2 exits.

    3. Finally, func3 calls func2 and contains an exception handler. When func2 throws the exception, func3 catches it.

    • The catch block prints the caught exception (404) and the execution continues.
    • The local object obj3 in func3 is destroyed at the end of the function.

    Important Points:

    • In the process of stack unwinding, destructors for local objects are called as each function is removed from the call stack.
    • Any code after the exception is thrown in func1 and func2 does not execute.
    • Stack unwinding ensures that resources are properly cleaned up, even when exceptions occur, preventing memory leaks or dangling resources.

    User-defined Custom Exception with class

    In C++, exceptions can be thrown using user-defined class types, allowing for more structured and meaningful error handling. For example, a custom class can be created to represent a specific kind of exception, and objects of that class can be thrown within a try block and caught in a catch block.

    Example 1: Exception Handling with a Single Class

    In this example, we define a simple class and throw an object of this class type in the try block. The object is caught in the corresponding catch block.

    #include <iostream>
    using namespace std;
    
    class CustomException {
    };
    
    int main() {
        try {
            throw CustomException();
        }
    
        catch (CustomException ce) {
            cout << "Caught an exception of CustomException class" << endl;
        }
    }

    Output:

    Caught an exception of CustomException class

    Explanation:
    Here, we define an empty class CustomException. In the try block, an object of this class is thrown using throw CustomException(). The catch block catches the exception and prints a message.

    Example 2: Exception Handling with Multiple Classes

    This example demonstrates how exceptions can be handled using multiple user-defined classes. Depending on the condition, different class objects are thrown and handled accordingly.

    #include <iostream>
    using namespace std;
    
    class ExceptionType1 {
    };
    
    class ExceptionType2 {
    };
    
    int main() {
        for (int i = 1; i <= 2; i++) {
            try {
                if (i == 1)
                    throw ExceptionType1();
                else if (i == 2)
                    throw ExceptionType2();
            }
    
            catch (ExceptionType1 et1) {
                cout << "Caught an exception of ExceptionType1 class" << endl;
            }
    
            catch (ExceptionType2 et2) {
                cout << "Caught an exception of ExceptionType2 class" << endl;
            }
        }
    }

    Output:

    Caught an exception of ExceptionType1 class
    Caught an exception of ExceptionType2 class

    Example 3: Exception Handling with Inheritance

    C++ exception handling can also involve inheritance. When an exception is thrown by a derived class, it can be caught by a catch block that handles the base class, due to the nature of polymorphism in inheritance.

    Example:

    #include <iostream>
    using namespace std;
    
    class BaseException {
    };
    
    class DerivedException : public BaseException {
    };
    
    int main() {
        for (int i = 1; i <= 2; i++) {
            try {
                if (i == 1)
                    throw BaseException();
                else if (i == 2)
                    throw DerivedException();
            }
    
            catch (BaseException be) {
                cout << "Caught an exception of BaseException class" << endl;
            }
    
            catch (DerivedException de) {
                cout << "Caught an exception of DerivedException class" << endl;
            }
        }
    }

    Output:

    Caught an exception of BaseException class
    Caught an exception of BaseException class

    Example 4: Exception Handling in Constructors

    Exception handling can also be implemented within constructors. Though constructors cannot return values, exceptions can be used to signal errors during object creation.

    Example:

    #include <iostream>
    using namespace std;
    
    class Example {
        int number;
    
    public:
        Example(int x) {
            try {
                if (x == 0)
                    throw "Zero is not allowed";
    
                number = x;
                display();
            }
            catch (const char* msg) {
                cout << "Exception caught: " << msg << endl;
            }
        }
    
        void display() {
            cout << "Number = " << number << endl;
        }
    };
    
    int main() {
        // Constructor is called and exception is handled
        Example obj1(0);
    
        cout << "Creating another object..." << endl;
    
        Example obj2(5);
    }

    Output:

    Exception caught: Zero is not allowed
    Creating another object...
    Number = 5
  • Virtual Function

    Virtual function in C++

    virtual function (also referred to as virtual methods) is a member function declared in a base class that can be overridden in a derived class. When a derived class object is referred to using a pointer or reference of the base class, the virtual function allows the derived class’s implementation to be executed.

    Virtual functions ensure the correct function is called based on the object type, regardless of the reference (or pointer) type used. They play a key role in enabling runtime polymorphism. Functions are declared using the virtual keyword in the base class, and their call resolution is performed at runtime.

    Key Rules for Virtual Functions
    • Virtual functions cannot be static.
    • They can be friends of another class.
    • To achieve runtime polymorphism, virtual functions should be accessed using a pointer or reference to a base class.
    • The function prototypes must be the same in the base and derived classes.
    • They are always defined in the base class and overridden in the derived class. If the derived class does not override the virtual function, the base class version will be used.
    • A class can have a virtual destructor but not a virtual constructor.
    Early Binding vs. Late Binding

    Virtual functions demonstrate late binding or runtime polymorphism, where the function call is resolved during runtime. In contrast, non-virtual functions exhibit early binding or compile-time binding, where the function call is resolved during compilation.

    Example: Runtime Behavior of Virtual Functions

    #include <iostream>
    using namespace std;
    
    class Base {
    public:
        virtual void display() { cout << "Base class display\n"; }
        void show() { cout << "Base class show\n"; }
    };
    
    class Derived : public Base {
    public:
        void display() { cout << "Derived class display\n"; }
        void show() { cout << "Derived class show\n"; }
    };
    
    int main() {
        Base* basePtr;
        Derived derivedObj;
        basePtr = &derivedObj;
    
        // Virtual function, resolved at runtime
        basePtr->display();
    
        // Non-virtual function, resolved at compile time
        basePtr->show();
    
        return 0;
    }

    Output:

    Derived class display
    Base class show

    Explanation: In this example, basePtr is a pointer of type Base, but it points to an object of type Derived. The virtual function display() is resolved at runtime, so the Derived class version is called. On the other hand, the non-virtual function show() is resolved at compile-time, and the Base class version is executed.

    Working of Virtual Functions (VTABLE and VPTR)

    When a class contains virtual functions, the compiler takes the following actions:

    1. For every class that contains a virtual function, the compiler creates a vtable (virtual table), which is a static array of function pointers. Each cell of the vtable stores the address of a virtual function in that class.
    2. For every object of a class containing virtual functions, a vptr (virtual pointer) is added as a hidden data member. This pointer refers to the vtable of the class to which the object belongs.

    This mechanism allows the correct virtual function to be called at runtime based on the actual object type.

    Example: Working of Virtual Functions

    #include <iostream>
    using namespace std;
    
    class Base {
    public:
        void func1() { cout << "Base - func1\n"; }
        virtual void func2() { cout << "Base - func2\n"; }
        virtual void func3() { cout << "Base - func3\n"; }
        virtual void func4() { cout << "Base - func4\n"; }
    };
    
    class Derived : public Base {
    public:
        void func1() { cout << "Derived - func1\n"; }
        void func2() { cout << "Derived - func2\n"; }
        void func4(int x) { cout << "Derived - func4 with parameter\n"; }
    };
    
    int main() {
        Base* basePtr;
        Derived derivedObj;
        basePtr = &derivedObj;
    
        // Early binding (compile-time)
        basePtr->func1();
    
        // Late binding (runtime)
        basePtr->func2();
    
        // Late binding (runtime)
        basePtr->func3();
    
        // Late binding (runtime)
        basePtr->func4();
    
        // Illegal: Early binding but function does not exist in base class
        // basePtr->func4(5);
    
        return 0;
    }

    Output:

    Base - func1
    Derived - func2
    Base - func3
    Base - func4
    Explanation:
    • func1() is a non-virtual function, so it is resolved at compile-time, and the Base class version is called.
    • func2() is a virtual function, so the Derived class version is called at runtime.
    • func3() and func4() are virtual functions, and since func3() is not overridden in the derived class, the Base class version is called. Similarly, func4() is also resolved to the Base class version.
    a < b  : 0
    a > b  : 1
    a <= b: 0
    a >= b: 1
    a == b: 0
    a != b : 1

    virtual function in a base class can be overridden by a derived class. When a derived class object is referenced or pointed to by a base class reference or pointer, calling a virtual function will invoke the version defined in the derived class.

    In C++, once a function is marked as virtual in a base class, it remains virtual throughout all derived classes. Therefore, you don’t need to explicitly declare it as virtual again in derived classes that override the function.

    For instance, in the example below, even though the keyword virtual is only used in the base class A, the function fun() in B and C is virtual. This is demonstrated by the fact that the program prints “C::fun() called”, as B::fun() inherits the virtual property.

    Example

    #include <iostream>
    using namespace std;
    
    class Animal {
    public:
        virtual void sound() { cout << "\n Animal sound"; }
    };
    
    class Dog : public Animal {
    public:
        void sound() { cout << "\n Dog barks"; }
    };
    
    class Puppy : public Dog {
    public:
        void sound() { cout << "\n Puppy squeaks"; }
    };
    
    int main() {
        // Create an object of class Puppy
        Puppy p;
    
        // Pointer of class Dog pointing to object of class Puppy
        Dog* dogPtr = &p;
    
        // This line prints "Puppy squeaks" due to the virtual function mechanism
        dogPtr->sound();
    
        return 0;
    }

    Output:

    Puppy squeaks

    Virtual Functions in Derived Classes

    virtual function is a member function in a base class that can be overridden in a derived class. When a pointer or reference to the base class is used to refer to an object of the derived class, the derived class’s version of the virtual function is executed.

    Once a function is marked as virtual in a base class in C++, it remains virtual throughout all derived classes. You don’t need to explicitly declare it as virtual in the derived classes when overriding it.

    For instance, in the following program, even though the keyword virtual is used only in class A, the function fun() in B and C behaves as virtual. As a result, the program outputs “C::display() called”, since the virtual function mechanism ensures that B::fun() is automatically virtual.

    Example

    #include <iostream>
    using namespace std;
    
    class Shape {
    public:
        virtual void draw() { cout << "\n Drawing Shape"; }
    };
    
    class Circle : public Shape {
    public:
        void draw() { cout << "\n Drawing Circle"; }
    };
    
    class FilledCircle : public Circle {
    public:
        void draw() { cout << "\n Drawing Filled Circle"; }
    };
    
    int main() {
        // Object of class FilledCircle
        FilledCircle filledCircle;
    
        // Pointer of class Circle pointing to object of FilledCircle
        Circle* circlePtr = &filledCircle;
    
        // This line prints "Drawing Filled Circle"
        circlePtr->draw();
    
        return 0;
    }

    Output:

    Drawing Filled Circle

    Default Arguments and Virtual Function

    Default arguments allow you to provide initial values in function declarations that will be used if no arguments are passed during a function call. If arguments are provided, the default values are overridden. Virtual functions, on the other hand, enable runtime polymorphism by allowing a derived class to override a function in the base class.

    Combining default arguments with virtual functions can lead to interesting behavior. Let’s explore how they work together.

    Example:

    #include <iostream>
    using namespace std;
    
    // Base class declaration
    class Animal {
    public:
        // Virtual function with a default argument
        virtual void sound(int volume = 5) {
            cout << "Animal sound at volume: " << volume << endl;
        }
    };
    
    // Derived class overriding the virtual function
    class Dog : public Animal {
    public:
        // Virtual function without a default argument
        virtual void sound(int volume) {
            cout << "Dog barks at volume: " << volume << endl;
        }
    };
    
    // Main function
    int main() {
        Dog dog;
    
        // Pointer to base class points to derived class object
        Animal* animalPtr = &dog;
    
        // Calls derived class function, default argument from base class
        animalPtr->sound();
    
        return 0;
    }

    Output:

    Dog barks at volume: 5

    Virtual Destructor

    Deleting a derived class object using a pointer of base class type that does not have a virtual destructor leads to undefined behavior. This is because when deleting an object through a base class pointer, only the base class destructor will be invoked, leaving the derived class destructor uncalled. To resolve this issue, the base class should be defined with a virtual destructor.

    Consider the following example, where the lack of a virtual destructor in the base class causes undefined behavior:

    // Example with non-virtual destructor, causing undefined behavior
    #include <iostream>
    
    class Base {
      public:
        Base() {
            std::cout << "Base class constructor\n";
        }
        ~Base() {
            std::cout << "Base class destructor\n";
        }
    };
    
    class Derived : public Base {
      public:
        Derived() {
            std::cout << "Derived class constructor\n";
        }
        ~Derived() {
            std::cout << "Derived class destructor\n";
        }
    };
    
    int main() {
        Derived* d = new Derived();
        Base* b = d;
        delete b; // Undefined behavior: Derived class destructor not called
        return 0;
    }

    Output:

    Base class constructor
    Derived class constructor
    Base class destructor

    As we can see, only the base class destructor is called, and the derived class destructor is skipped, leading to potential memory leaks or other issues.

    To ensure both base and derived destructors are properly invoked, we must make the base class destructor virtual, as shown in the following example:

    // Example with virtual destructor
    #include <iostream>
    
    class Base {
      public:
        Base() {
            std::cout << "Base class constructor\n";
        }
        virtual ~Base() {
            std::cout << "Base class destructor\n";
        }
    };
    
    class Derived : public Base {
      public:
        Derived() {
            std::cout << "Derived class constructor\n";
        }
        ~Derived() {
            std::cout << "Derived class destructor\n";
        }
    };
    
    int main() {
        Derived* d = new Derived();
        Base* b = d;
        delete b; // Both base and derived destructors are called
        return 0;
    }

    Output:

    Base class constructor
    Derived class constructor
    Derived class destructor
    Base class destructor

    Virtual Constructor

    In C++, we cannot make a constructor virtual. The reason is that C++ is a statically typed language, and a virtual constructor contradicts this because the compiler needs to determine the exact type at compile time to allocate the right amount of memory and initialize the object properly.

    Attempting to declare a constructor as virtual will result in a compiler error. In fact, apart from the inline keyword, no other keyword is permitted in constructor declarations.

    Problem: Tightly Coupled Object Creation

    In real-world scenarios, you may want to instantiate objects from a class hierarchy based on runtime conditions or user input. However, object creation in C++ is tightly coupled to specific class types, meaning that whenever a new class is added to a hierarchy, code changes and recompilation are required.

    For instance, consider a situation where the User class always creates an object of type Derived1. If at some point you want to create an object of Derived2, you would need to modify the User class to instantiate Derived2 instead, which forces recompilation—a design flaw.

    Example of Tight Coupling

    Here’s an example of how object creation can lead to tight coupling:

    // C++ program showing tight coupling issue in object creation
    #include <iostream>
    using namespace std;
    
    class Base {
      public:
        Base() {}
    
        virtual ~Base() {}
    
        virtual void DisplayAction() = 0;
    };
    
    class Derived1 : public Base {
      public:
        Derived1() {
            cout << "Derived1 created\n";
        }
        ~Derived1() {
            cout << "Derived1 destroyed\n";
        }
        void DisplayAction() {
            cout << "Action from Derived1\n";
        }
    };
    
    class Derived2 : public Base {
      public:
        Derived2() {
            cout << "Derived2 created\n";
        }
        ~Derived2() {
            cout << "Derived2 destroyed\n";
        }
        void DisplayAction() {
            cout << "Action from Derived2\n";
        }
    };
    
    class User {
      public:
        User() : pBase(nullptr) {
            pBase = new Derived1();  // Always creating Derived1
            // But what if Derived2 is needed?
        }
        ~User() {
            delete pBase;
        }
    
        void Action() {
            pBase->DisplayAction();
        }
    
      private:
        Base *pBase;
    };
    
    int main() {
        User *user = new User();
        user->Action();
        delete user;
    }

    Output:

    Derived1 created
    Action from Derived1
    Derived1 destroyed

    In this example, the User class is tightly coupled to Derived1. If a consumer requires the functionality of Derived2, the User class must be modified and recompiled to create Derived2. This is inflexible and leads to poor design.

    Methods for Decoupling

    Here are common methods to decouple tightly coupled classes:

    1. Modifying with an If-Else Ladder (Not Extensible) : One way to address this issue is by adding an if-else ladder to select the desired derived class based on input. However, this solution still suffers from the same problem.

    // C++ program showing how to use if-else for object creation
    #include <iostream>
    using namespace std;
    
    class Base {
      public:
        Base() {}
        virtual ~Base() {}
        virtual void DisplayAction() = 0;
    };
    
    class Derived1 : public Base {
      public:
        Derived1() {
            cout << "Derived1 created\n";
        }
        ~Derived1() {
            cout << "Derived1 destroyed\n";
        }
        void DisplayAction() {
            cout << "Action from Derived1\n";
        }
    };
    
    class Derived2 : public Base {
      public:
        Derived2() {
            cout << "Derived2 created\n";
        }
        ~Derived2() {
            cout << "Derived2 destroyed\n";
        }
        void DisplayAction() {
            cout << "Action from Derived2\n";
        }
    };
    
    class User {
      public:
        User() : pBase(nullptr) {
            int input;
            cout << "Enter ID (1 or 2): ";
            cin >> input;
    
            if (input == 1)
                pBase = new Derived1();
            else
                pBase = new Derived2();
        }
    
        ~User() {
            delete pBase;
        }
    
        void Action() {
            pBase->DisplayAction();
        }
    
      private:
        Base *pBase;
    };
    
    int main() {
        User *user = new User();
        user->Action();
        delete user;
    }

    Output:

    Enter ID (1 or 2): 2
    Derived2 created
    Action from Derived2
    Derived2 destroyed

    This approach is still not extensible. If another derived class, Derived3, is added to the hierarchy, the User class must be updated and recompiled.

    2. The Factory Method (Best Solution) : A better solution is to delegate the responsibility of object creation to the class hierarchy itself or a static function, thereby decoupling the User class from the derived classes. This approach is known as the Factory Method.

    // C++ program using Factory Method for object creation
    #include <iostream>
    using namespace std;
    
    class Base {
      public:
        static Base* Create(int id);
    
        Base() {}
        virtual ~Base() {}
    
        virtual void DisplayAction() = 0;
    };
    
    class Derived1 : public Base {
      public:
        Derived1() {
            cout << "Derived1 created\n";
        }
        ~Derived1() {
            cout << "Derived1 destroyed\n";
        }
        void DisplayAction() {
            cout << "Action from Derived1\n";
        }
    };
    
    class Derived2 : public Base {
      public:
        Derived2() {
            cout << "Derived2 created\n";
        }
        ~Derived2() {
            cout << "Derived2 destroyed\n";
        }
        void DisplayAction() {
            cout << "Action from Derived2\n";
        }
    };
    
    Base* Base::Create(int id) {
        if (id == 1) return new Derived1();
        else return new Derived2();
    }
    
    class User {
      public:
        User() : pBase(nullptr) {
            int input;
            cout << "Enter ID (1 or 2): ";
            cin >> input;
            pBase = Base::Create(input);
        }
    
        ~User() {
            delete pBase;
        }
    
        void Action() {
            pBase->DisplayAction();
        }
    
      private:
        Base *pBase;
    };
    
    int main() {
        User *user = new User();
        user->Action();
        delete user;
    }

    Output:

    Enter ID (1 or 2): 1
    Derived1 created
    Action from Derived1
    Derived1 destroyed

    Virtual Copy Constructor

    In the virtual constructor idiom, we have seen how to construct an object whose type is determined at runtime. But is it possible to copy an object without knowing its exact type at compile time? The virtual copy constructor addresses this problem.

    Sometimes, we need to create a new object based on the state of an existing object. Typically, this is done using the copy constructor, which initializes the new object with the state of the existing one. The compiler invokes the copy constructor when an object is instantiated from another. However, the compiler must know the exact type of the object to invoke the appropriate copy constructor.

    Example Without Virtual Copy Constructor:

    #include <iostream>
    using namespace std;
    
    class Base {
        // Base class
    };
    
    class Derived : public Base {
    public:
        Derived() {
            cout << "Derived created" << endl;
        }
    
        // Copy constructor
        Derived(const Derived &rhs) {
            cout << "Derived created by deep copy" << endl;
        }
    
        ~Derived() {
            cout << "Derived destroyed" << endl;
        }
    };
    
    int main() {
        Derived d1;
        Derived d2 = d1;  // Compiler calls the copy constructor
    
        // How to copy a Derived object through a Base pointer?
        return 0;
    }
    Problem: Copying at Runtime Without Knowing Type

    The virtual constructor creates objects of a derived class based on runtime input. When we want to copy one of these objects, we can’t use the regular copy constructor because the exact type of the object isn’t known at compile time. Instead, we need a virtual function that can duplicate the object during runtime, based on its actual type.

    Consider a drawing application where users can select an object and duplicate it. The type of object (circle, square, etc.) isn’t known until runtime, so the virtual copy constructor (or a clone function) is needed to correctly copy and paste the object.

    Updated Example Using Virtual Copy Constructor:

    Prefix Increment: Increases the operand’s value before it is used in an expression.

    #include <iostream>
    using namespace std;
    
    // Base class
    class Base {
    public:
        Base() {}
    
        // Virtual destructor to ensure correct cleanup
        virtual ~Base() {}
    
        // Pure virtual function to change object attributes
        virtual void ModifyAttributes() = 0;
    
        // Virtual constructor
        static Base* Create(int id);
    
        // Virtual copy constructor
        virtual Base* Clone() = 0;
    };
    
    // Derived1 class
    class Derived1 : public Base {
    public:
        Derived1() {
            cout << "Derived1 created" << endl;
        }
    
        // Copy constructor
        Derived1(const Derived1& rhs) {
            cout << "Derived1 created by deep copy" << endl;
        }
    
        ~Derived1() {
            cout << "~Derived1 destroyed" << endl;
        }
    
        void ModifyAttributes() {
            cout << "Derived1 attributes modified" << endl;
        }
    
        // Clone method (virtual copy constructor)
        Base* Clone() {
            return new Derived1(*this);
        }
    };
    
    // Derived2 class
    class Derived2 : public Base {
    public:
        Derived2() {
            cout << "Derived2 created" << endl;
        }
    
        // Copy constructor
        Derived2(const Derived2& rhs) {
            cout << "Derived2 created by deep copy" << endl;
        }
    
        ~Derived2() {
            cout << "~Derived2 destroyed" << endl;
        }
    
        void ModifyAttributes() {
            cout << "Derived2 attributes modified" << endl;
        }
    
        // Clone method (virtual copy constructor)
        Base* Clone() {
            return new Derived2(*this);
        }
    };
    
    // Derived3 class
    class Derived3 : public Base {
    public:
        Derived3() {
            cout << "Derived3 created" << endl;
        }
    
        // Copy constructor
        Derived3(const Derived3& rhs) {
            cout << "Derived3 created by deep copy" << endl;
        }
    
        ~Derived3() {
            cout << "~Derived3 destroyed" << endl;
        }
    
        void ModifyAttributes() {
            cout << "Derived3 attributes modified" << endl;
        }
    
        // Clone method (virtual copy constructor)
        Base* Clone() {
            return new Derived3(*this);
        }
    };
    
    // Factory method to create objects at runtime
    Base* Base::Create(int id) {
        if (id == 1)
            return new Derived1;
        else if (id == 2)
            return new Derived2;
        else
            return new Derived3;
    }
    
    // Utility class to use Base objects
    class User {
    public:
        User() : pBase(nullptr) {
            int id;
            cout << "Enter ID (1, 2, or 3): ";
            cin >> id;
    
            // Create object at runtime using factory method
            pBase = Base::Create(id);
        }
    
        ~User() {
            if (pBase) {
                delete pBase;
                pBase = nullptr;
            }
        }
    
        void PerformAction() {
            // Clone the current object (runtime copy)
            Base* clonedObj = pBase->Clone();
    
            // Modify the cloned object's attributes
            clonedObj->ModifyAttributes();
    
            // Cleanup the cloned object
            delete clonedObj;
        }
    
    private:
        Base* pBase;
    };
    
    // Client code
    int main() {
        User* user = new User();
        user->PerformAction();
        delete user;
    
        return 0;
    }

    Pure Virtual Functions and Abstract Classes

    Sometimes, we may not provide the complete implementation of all functions in a base class because the specifics are not known. Such a class is called an abstract class. For example, consider a base class called Shape. We cannot define how draw() works in the base class, but every derived class (like CircleRectangle, etc.) must provide an implementation for draw(). Similarly, an Animal class might have a move() function that all animals need to implement, but the way they move may differ. We cannot create objects of abstract classes.

    pure virtual function (also known as an abstract function) in C++ is a virtual function that has no definition in the base class, and we force derived classes to provide an implementation. If a derived class does not override this function, the derived class will also become an abstract class. A pure virtual function is declared by assigning it a value of 0 in its declaration.

    Example of a Pure Virtual Function:

    // Abstract class
    class AbstractClass {
    public:
        // Pure Virtual Function
        virtual void display() = 0;
    };

    Complete Example:  A pure virtual function must be implemented by any class that is derived from an abstract class.

    #include <iostream>
    using namespace std;
    
    class Base {
        // Private data member
        int x;
    
    public:
        // Pure virtual function
        virtual void show() = 0;
    
        // Getter function to access x
        int getX() { return x; }
    };
    
    // Derived class implementing the pure virtual function
    class Derived : public Base {
        // Private data member
        int y;
    
    public:
        // Implementation of the pure virtual function
        void show() { cout << "show() function called" << endl; }
    };
    
    int main() {
        // Creating an object of the Derived class
        Derived d;
    
        // Calling the show() function
        d.show();
    
        return 0;
    }

    Output:

    show() function called
    Key Points

    1. Abstract Classes: A class becomes abstract if it contains at least one pure virtual function.

    Example: In the code below, the class Example is abstract because it has a pure virtual function display().

    #include <iostream>
    using namespace std;
    
    class Example {
        int x;
    
    public:
        // Pure virtual function
        virtual void display() = 0;
    
        // Getter function for x
        int getX() { return x; }
    };
    
    int main() {
        // Error: Cannot instantiate an abstract class
        Example ex;
    
        return 0;
    }

    Output:

    Compiler Error: Cannot instantiate an abstract class

    The compiler will throw an error because Example is an abstract class, and we cannot create an object of it.

    2. Pointers and References to Abstract Classes: Although you cannot instantiate an abstract class, you can create pointers and references to it. This allows polymorphism, where a pointer to an abstract class can point to any derived class object.

    Example:

    #include <iostream>
    using namespace std;
    
    class Base {
    public:
        // Pure virtual function
        virtual void show() = 0;
    };
    
    class Derived : public Base {
    public:
        // Implementation of the pure virtual function
        void show() { cout << "Derived class implementation" << endl; }
    };
    
    int main() {
        // Pointer to Base class pointing to Derived object
        Base* ptr = new Derived();
    
        // Calling the show() function via the pointer
        ptr->show();
    
        delete ptr;
        return 0;
    }

    Output:

    Derived class implementation

    3. Derived Classes Become Abstract: If a derived class does not override the pure virtual function, it will also be treated as an abstract class, meaning you cannot instantiate it.

    Example:

    #include <iostream>
    using namespace std;
    
    class Base {
    public:
        // Pure virtual function
        virtual void show() = 0;
    };
    
    class Derived : public Base {
        // No override for the pure virtual function
    };
    
    int main() {
        // Error: Cannot create an object of an abstract class
        Derived d;
    
        return 0;
    }

    Output:

    Compiler Error: Derived is an abstract class because 'show()' is not implemented

    Pure Virtual Destructor in C++

    Can a Destructor Be Pure Virtual in C++?

    Yes, in C++, a destructor can be declared as pure virtual. Pure virtual destructors are legal and serve an essential role, especially in abstract base classes. However, if a class contains a pure virtual destructor, you must provide a definition for the destructor. This requirement arises from the fact that destructors are not overridden like other functions but are always called in reverse order of class inheritance. Without a definition for the pure virtual destructor, there will be no valid function body to call during object destruction.

    Why Must a Pure Virtual Destructor Have a Body?

    The reason behind this requirement is that destructors are always invoked in reverse order during the destruction of objects. When a derived class object is deleted, its destructor is called first, followed by the base class destructor. Since the base class destructor must still execute, a function body is needed, even for pure virtual destructors. This ensures that resources allocated by the base class are cleaned up properly when an object is destroyed.

    Example of a Pure Virtual Destructor

    #include <iostream>
    using namespace std;
    
    // Base class with a pure virtual destructor
    class Base {
    public:
        virtual ~Base() = 0; // Pure virtual destructor
    };
    
    // Definition of the pure virtual destructor
    Base::~Base() {
        cout << "Base class destructor called\n";
    }
    
    // Derived class implementing its destructor
    class Derived : public Base {
    public:
        ~Derived() { cout << "Derived class destructor called\n"; }
    };
    
    // Driver code
    int main() {
        Base* ptr = new Derived();
        delete ptr;
        return 0;
    }

    Output:

    Derived class destructor called
    Base class destructor called

    In the example above, both the derived class and base class destructors are called in reverse order, ensuring proper cleanup.

    How It Works

    This works because destructors are always called in reverse order, starting from the most derived class back to the base class. When the delete operator is called on a pointer to a derived object, the derived class destructor is executed first, followed by the base class destructor. This is only possible because we provided a definition for the pure virtual destructor in the base class.

    Important Points

    Example: Demonstrating Abstract Class with Pure Virtual Destructor

    #include <iostream>
    using namespace std;
    
    class AbstractClass {
    public:
        // Pure virtual destructor
        virtual ~AbstractClass() = 0;
    };
    
    // Defining the pure virtual destructor
    AbstractClass::~AbstractClass() {
        cout << "AbstractClass destructor called\n";
    }
    
    // Attempting to create an object of AbstractClass will result in an error
    int main() {
        // AbstractClass obj;  // This will cause a compiler error
        return 0;
    }
    Error: Cannot instantiate abstract class ‘AbstractClass’ because its destructor is pure virtual.

    This error occurs because AbstractClass is abstract, meaning it contains a pure virtual function, making it impossible to instantiate. The error message confirms that the pure virtual destructor makes the class abstract.

    Can Static Functions Be Virtual in C++?

    In C++, static member functions of a class cannot be virtual. Virtual functions are invoked through a pointer or reference to an object of the class, allowing polymorphic behavior. However, static member functions are associated with the class itself, rather than any specific instance of the class. This distinction prevents them from being virtual, as there is no object to refer to for invoking them virtually.

    Example Demonstrating Static Functions Cannot Be Virtual

    Attempting to declare a static member function as virtual will result in a compilation error:

    // C++ program demonstrating that static member functions
    // cannot be virtual
    #include <iostream>
    
    class Example {
    public:
        virtual static void display() {}
    };
    
    int main() {
        Example e;
        return 0;
    }

    Output:

    error: member ‘display’ cannot be declared both virtual and static

    The error occurs because C++ does not allow the combination of virtual and static for member functions, as static functions are tied to the class, not to specific instances.

    Static Member Functions Cannot Be const or volatile

    Static member functions are also not allowed to be declared const or volatile. Since const and volatile qualifiers are applied to member functions to indicate whether they can modify the state of the object or respond to volatility, static functions—being associated with the class rather than instances—cannot access instance-specific data members, making these qualifiers meaningless.

    Example Demonstrating Static Member Functions Cannot Be const

    Attempting to declare a static member function as const will also fail at compile time:

    // C++ program demonstrating that static member functions
    // cannot be const
    #include <iostream>
    
    class Example {
    public:
        static void display() const {}
    };
    
    int main() {
        Example e;
        return 0;
    }

    Example:

    error: static member function ‘static void Example::display()’ cannot have cv-qualifier

    Run-time Type Information (RTTI) in C++

    In this example, we demonstrate how dynamic_cast fails when the base class does not contain a virtual function. Since RTTI (Run-Time Type Information) requires at least one virtual function in the base class for dynamic_cast to function, this example will lead to a runtime failure.

    #include <iostream>
    using namespace std;
    
    // Base class without a virtual function
    class Base {};
    
    // Derived class inheriting from Base
    class Derived : public Base {};
    
    int main() {
        Base* basePtr = new Derived; // Base class pointer pointing to a Derived object
        // Attempting to downcast using dynamic_cast
        Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
    
        if (derivedPtr != nullptr)
            cout << "Cast successful" << endl;
        else
            cout << "Cannot cast Base* to Derived*" << endl;
    
        return 0;
    }

    Expected Output:

    Cannot cast Base* to Derived*

    Here, the dynamic_cast fails because there is no virtual function in the base class Base, which makes RTTI unavailable. As a result, the cast does not succeed.

    Adding a Virtual Function to Enable RTTI

    By adding a virtual function to the base class, RTTI is enabled, allowing dynamic_cast to perform the necessary checks at runtime and making the cast succeed.

    Example With a Virtual Function in the Base Class

    #include <iostream>
    using namespace std;
    
    // Base class with a virtual function
    class Base {
    public:
        virtual void exampleFunction() {} // Virtual function to enable RTTI
    };
    
    // Derived class inheriting from Base
    class Derived : public Base {};
    
    int main() {
        Base* basePtr = new Derived; // Base class pointer pointing to a Derived object
        // Attempting to downcast using dynamic_cast
        Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
    
        if (derivedPtr != nullptr)
            cout << "Cast successful" << endl;
        else
            cout << "Cannot cast Base* to Derived*" << endl;
    
        return 0;
    }

    Expected Output:

    Cast successful