Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Sunday, September 6, 2026

September 06, 2026

Inline Functions, Static Class Members, Scope Resolution Operator, Nested Classes and Local Classes

Inline Functions, Static Class Members, Scope Resolution Operator, Nested Classes and Local Classes in C++

 

1. Inline Functions

Definition

An inline function is a function in which the compiler is requested to replace the function call with the actual function code at the point of the call. This can reduce the overhead associated with a normal function call, particularly for small and frequently called functions.

The inline keyword is used to request inline expansion.

Syntax

inline return_type function_name(parameters)

{

    // function body

}

 

Example

#include <iostream>

using namespace std;

 

inline int square(int n)

{

    return n * n;

}

 

int main()

{

    cout << "Square = " << square(5);

 

    return 0;

}

Output

Square = 25

Important Points

  1. The inline keyword requests the compiler to perform inline expansion.
  2. It is generally suitable for small functions.
  3. Inline expansion can reduce function-call overhead.
  4. The compiler may ignore the inline request when it considers expansion unsuitable.
  5. A function defined inside a class definition is implicitly inline.
  6. Large, recursive, or complex functions are generally not good candidates for inline expansion.
  7. inline does not guarantee that the function will actually be expanded inline.

Example of an Inline Member Function

class Calculator

{

public:

    int add(int a, int b)

    {

        return a + b;

    }

};

Here, add() is implicitly an inline member function because it is defined inside the class.

 

2. Static Class Members

A static class member belongs to the class rather than to individual objects.

There are two commonly discussed types:

  1. Static data member
  2. Static member function

 

2.1 Static Data Member

Definition

A static data member has only one shared copy for the entire class, regardless of how many objects of that class are created.

Syntax

class ClassName

{

    static data_type variable;

};

The static data member is normally defined outside the class:

data_type ClassName::variable = value;

Example

#include <iostream>

using namespace std;

class Student

{

public:

    static int count;

 

    Student()

    {

        count++;

    }

};

 

int Student::count = 0;

 

int main()

{

    Student s1;

    Student s2;

    Student s3;

 

    cout << "Number of objects = " << Student::count;

 

    return 0;

}

Output

Number of objects = 3

Explanation

Here:

static int count;

is shared by all objects of the Student class.

When three objects are created, the same count variable is incremented three times.

Important Points

  • Only one copy of a static data member exists for the class.
  • It is shared by all objects.
  • It can be accessed using the class name:

Student::count

  • Traditionally, a static data member requires an out-of-class definition when odr-used; modern C++ also provides inline static data members, which can be defined directly inside the class.

 

2.2 Static Member Function

Definition

A static member function belongs to the class rather than to a particular object.

Syntax

class ClassName

{

public:

    static return_type functionName()

    {

        // function body

    }

};

Example

#include <iostream>

using namespace std;

class Math

{

public:

    static int square(int n)

    {

        return n * n;

    }

};

 

int main()

{

    cout << Math::square(6);

 

    return 0;

}

Output

36

Important Points

A static member function:

  • Can be called using the class name.
  • Does not require an object for invocation.
  • Does not have a this pointer.
  • Can directly access static members of the class.
  • Cannot directly access non-static data members.

 

3. Scope Resolution Operator (::)

Definition

The scope resolution operator (::) is used to specify the scope to which an identifier belongs.

It is one of the important operators in C++ and is particularly useful for defining class member functions outside the class.

Syntax

ClassName::memberName

Example 1: Defining a Member Function Outside the Class

#include <iostream>

using namespace std;

class Student

{

private:

    int rollNo;

 

public:

    void setRollNo(int r);

    void display();

};

 

void Student::setRollNo(int r)

{

    rollNo = r;

}

 

void Student::display()

{

    cout << "Roll No: " << rollNo;

}

 

int main()

{

    Student s;

 

    s.setRollNo(101);

    s.display();

 

    return 0;

}

Output

Roll No: 101

Here:

void Student::display()

means that display() belongs to the Student class.

Major Uses of ::

Use

Example

Define class member outside class

void Student::display()

Access static class member

Student::count

Access namespace member

std::cout

Access global variable when hidden by local variable

::x

Access nested class/type

Outer::Inner

 

Example: Global Variable

#include <iostream>

using namespace std;

 

int x = 100;

 

int main()

{

    int x = 50;

 

    cout << "Local x: " << x << endl;

    cout << "Global x: " << ::x;

 

    return 0;

}

Output

Local x: 50

Global x: 100

 

4. Nested Classes

Definition

A nested class is a class that is declared inside another class.

The class containing the nested class is called the outer class, and the class declared inside it is called the nested or inner class.

Syntax

class Outer

{

public:

 

    class Inner

    {

        // members of Inner

    };

};

Example

#include <iostream>

using namespace std;

 

class Outer

{

public:

    class Inner

    {

    public:

        void display()

        {

            cout << "This is a nested class.";

        }

    };

};

 

int main()

{

    Outer::Inner obj;

 

    obj.display();

 

    return 0;

}

Output

This is a nested class.

Explanation

The nested class is accessed using the scope resolution operator:

Outer::Inner

and an object is created as:

Outer::Inner obj;

Important Points

  1. A nested class is defined inside another class.
  2. It helps logically group a class that is strongly related to its enclosing class.
  3. The nested class name is within the scope of the outer class.
  4. The scope resolution operator :: is used to refer to the nested class from outside.
  5. A nested class does not automatically have access to a particular object of the outer class.
  6. A nested class can have its own data members and member functions.

Real-Life Example

A University class could contain a nested Department class:

class University

{

public:

    class Department

    {

        // Department-related members

    };

};

This represents a logical relationship:

University → Department

 

5. Local Classes

Definition

A local class is a class that is declared inside a function or a local block.

Its scope is limited to the block in which it is declared.

Syntax

void function()

{

    class LocalClass

    {

        // members

    };

 

    LocalClass obj;

}

Example

#include <iostream>

using namespace std;

 

void display()

{

    class Number

    {

    public:

        void show()

        {

            cout << "This is a local class.";

        }

    };

 

    Number n;

    n.show();

}

 

int main()

{

    display();

 

    return 0;

}

Output

This is a local class.

Important Points

  1. A local class is declared inside a function or block.
  2. Its scope is restricted to that function/block.
  3. Its objects can normally be created only within that scope.
  4. It is useful when a class is required only for a particular function.
  5. A local class cannot have static data members in the traditional sense; modern C++ has some nuanced exceptions around static/inline members, but this is generally not needed at introductory level.
  6. A local class cannot have member templates.
  7. It cannot directly access automatic local variables of the enclosing function unless those values are passed to it or otherwise made available through permitted mechanisms.

 

Quick Revision Table

Topic

Meaning

Main Keyword/Operator

Main Feature

Inline Function

Small function requested for inline expansion

inline

Can reduce function-call overhead

Static Data Member

Class-level shared variable

static

One shared copy for the class

Static Member Function

Class-level function

static

Can be called without an object

Scope Resolution Operator

Specifies scope of an identifier

::

Defines/accesses class, namespace and global members

Nested Class

Class declared inside another class

class + ::

Provides logical grouping

Local Class

Class declared inside a function/block

class

Scope limited to the function/block

 

 

Very Short Exam Definitions

Inline Function:
An inline function is a function for which the compiler is requested to substitute the function body at the point of the function call.

Static Class Member:
A static class member belongs to the class as a whole and is shared by all objects of that class.

Scope Resolution Operator:
The scope resolution operator :: is used to specify and access the scope of an identifier.

Nested Class:
A nested class is a class declared within another class.

Local Class:
A local class is a class declared inside a function or block, whose scope is restricted to that function or block.

 


September 06, 2026

Searching: Linear Search and Binary Search


Searching: Linear Search and Binary Search

 

Searching is one of the fundamental operations performed on a data structure. Searching means finding whether a particular element, called the key, is present in a collection of elements and, if present, determining its position.

For example, if an array contains:

10, 25, 30, 45, 60

and the key is 45, the searching operation determines that 45 is present at index 3.

The two basic searching techniques are:

  1. Linear Search
  2. Binary Search

 

1. Linear Search

Definition

Linear Search, also called Sequential Search, is the simplest searching technique. In this method, each element of the array is compared sequentially with the key until:

  • the required element is found, or
  • the entire array has been examined.

It does not require the array to be sorted.

Example

Consider:

A = {10, 25, 30, 45, 60}

Suppose the key is 45.

The search proceeds as:

10 → 25 → 30 → 45

                 

                Found

The key is found at index 3.

 

Algorithm for Linear Search

Algorithm LinearSearch(A, n, key)

 

1. Start

2. For i = 0 to n-1

      If A[i] == key

          Return i

3. Return -1

4. Stop

Here:

  • A = array
  • n = number of elements
  • key = element to be searched
  • i = index of the current element
  • -1 indicates that the element is not found.

 

C Program: Linear Search

#include <stdio.h>

 

int main()

{

    int a[100], n, key, i, found = 0;

 

    printf("Enter number of elements: ");

    scanf("%d", &n);

 

    printf("Enter elements:\n");

    for(i = 0; i < n; i++)

        scanf("%d", &a[i]);

 

    printf("Enter element to search: ");

    scanf("%d", &key);

 

    for(i = 0; i < n; i++)

    {

        if(a[i] == key)

        {

            printf("Element found at index %d\n", i);

            found = 1;

            break;

        }

    }

 

    if(found == 0)

        printf("Element not found\n");

 

    return 0;

}

 

Working

If the input is:

Array = 12 25 37 48 59

Key = 37

The comparisons are:

12 == 37 → No

25 == 37 → No

37 == 37 → Yes

Therefore, the element is found at index 2.

 

2. Complexity Analysis of Linear Search

Suppose there are n elements.

Best Case

The key is present at the first position.

Only one comparison is required.

Worst Case

The key is:

  • present at the last position, or
  • not present in the array.

Therefore, approximately n comparisons are required.

Average Case

On average, approximately n/2 elements are examined.

Although the number of comparisons is approximately n/2, constants are ignored in asymptotic analysis.

Space Complexity

Linear search requires only a constant amount of additional memory.

 

3. Binary Search

Definition

Binary Search is an efficient searching technique that repeatedly divides a sorted array into two halves.

Unlike linear search, binary search requires the data to be sorted.

The basic principle is:

Compare the key with the middle element and eliminate the half in which the key cannot exist.

 

Example

Consider the sorted array:

A = {10, 20, 30, 40, 50, 60, 70}

Search key:

60

Initially:

10   20   30   40   50   60   70

              

             Middle

Middle element = 40

Since:

60 > 40

the left half can be discarded.

Remaining portion:

50   60   70

    

   Middle

Middle element = 60

Therefore:

60 == 60

Element found.

 

4. Algorithm for Binary Search

Algorithm BinarySearch(A, n, key)

 

1. Start

2. Set low = 0

3. Set high = n - 1

4. Repeat while low <= high

      mid = (low + high) / 2

 

      If A[mid] == key

          Return mid

 

      Else if key < A[mid]

          high = mid - 1

 

      Else

          low = mid + 1

 

5. Return -1

6. Stop

Important Variables

Variable

Meaning

low

Starting index of current search range

high

Ending index of current search range

mid

Middle index

key

Element being searched

 

5. C Program: Binary Search

#include <stdio.h>

int main()

{

    int a[100], n, key;

    int low, high, mid;

    int found = 0;

    printf("Enter number of elements: ");

    scanf("%d", &n);

    printf("Enter elements in sorted order:\n");

    for(int i = 0; i < n; i++)

        scanf("%d", &a[i]);

    printf("Enter element to search: ");

    scanf("%d", &key);

    low = 0;

    high = n - 1;

 

    while(low <= high)

    {

        mid = low + (high - low) / 2;

        if(a[mid] == key)

        {

            printf("Element found at index %d\n", mid);

            found = 1;

            break;

        }

        else if(key < a[mid])

        {

            high = mid - 1;

        }

        else

        {

            low = mid + 1;

        }

    }

    if(found == 0)

        printf("Element not found\n");

 

    return 0;

}

 

Why use

mid = low + (high - low) / 2;

instead of:

mid = (low + high) / 2;

The first expression is generally preferred because it avoids integer overflow when low and high are very large.

 

6. Complexity Analysis of Binary Search

At every step, binary search reduces the search space approximately by half.

For n elements:

n

n/2

n/4

n/8

...

1

After k divisions:

Therefore:

Taking logarithm:

Hence, the time complexity is:

Best Case

The key is the middle element in the first comparison.

Worst Case

The search continues until the search interval becomes empty or the key is found near the end of the process.

Average Case

Space Complexity

For the iterative implementation shown above:

If binary search is implemented recursively, the recursion stack requires:

 

7. Linear Search vs Binary Search

Basis

Linear Search

Binary Search

Basic principle

Checks elements sequentially

Repeatedly divides the search space into two halves

Data requirement

Sorted or unsorted data

Data must be sorted

Searching method

Sequential

Divide and conquer

Best-case time

O(1)

O(1)

Average-case time

O(n)

O(log n)

Worst-case time

O(n)

O(log n)

Space complexity (iterative)

O(1)

O(1)

Implementation

Very simple

Relatively more complex

Suitable for

Small or unsorted datasets

Large sorted datasets

Random access requirement

Not necessary

Generally most suitable with random-access structures such as arrays

Sorting required

No

Yes, if data is initially unsorted

Main advantage

Simple and works on unsorted data

Much faster for large sorted datasets

Main limitation

Slow for large datasets

Cannot directly be used on unsorted data

 

8. Complexity Comparison

For n = 1,000,000 elements:

Linear Search

Worst case:

It may need to inspect approximately one million elements.

Binary Search

Thus, binary search can locate an element in roughly 20 iterations in the worst case, assuming the array is already sorted.

This demonstrates why binary search is highly efficient for large sorted arrays.


9. Important Examination Points

Linear Search

  • Also known as Sequential Search.
  • Checks elements one by one.
  • Works on sorted as well as unsorted data.
  • Best-case complexity: O(1).
  • Average-case complexity: O(n).
  • Worst-case complexity: O(n).
  • Space complexity: O(1) for the iterative implementation.

Binary Search

  • Requires a sorted array.
  • Uses the divide-and-conquer principle.
  • Compares the search key with the middle element.
  • Eliminates approximately half of the search space after every comparison.
  • Best-case complexity: O(1).
  • Average-case complexity: O(log n).
  • Worst-case complexity: O(log n).
  • Iterative space complexity: O(1).
  • Recursive space complexity: O(log n).

Key Formula

For binary search:

For linear search:

In short: Use Linear Search when simplicity or unsorted data is important; use Binary Search when the data is sorted and efficient searching is required.