Unit 1 - Notes

CSE202

Unit 1: Concepts and Basics of C++ Programming and Functions

1. Procedural vs. Object-Oriented Programming Paradigms

Understanding the shift from C (Procedural) to C++ (Object-Oriented) is fundamental to mastering the language.

Procedural Programming (POP)

  • Focus: Focuses on functions and procedures (algorithms). The emphasis is on "doing things" (verbs).
  • Structure: The program is divided into small parts called functions.
  • Data Movement: Data moves openly around the system from function to function. Global data is often shared, leading to security and debugging issues.
  • Approach: Top-Down approach (Main program sub-functions).

Object-Oriented Programming (OOP)

  • Focus: Focuses on objects that contain both data and the functions that operate on that data. The emphasis is on the entities (nouns).
  • Structure: The program is divided into objects.
  • Data Movement: Data is hidden and cannot be accessed by external functions (Encapsulation). This ensures data security.
  • Approach: Bottom-Up approach (Design objects/classes integrate them).

Comparison Table:

Feature Procedural Programming Object-Oriented Programming
Primary Unit Function Class/Object
Data Security Low (Global data accessible freely) High (Data hiding/Encapsulation)
Overloading Not supported Supports function and operator overloading
Inheritance No Yes (Code reusability)
Access Specifiers None Public, Private, Protected
Examples C, Pascal, FORTRAN C++, Java, Python

2. Input/Output Streams and Basics

C++ uses the concept of "streams" (sequences of bytes) for I/O operations.

Features of Input/Output Streams

  • Header File: <iostream> must be included.
  • Namespace: Standard stream objects are defined within the std namespace.
  • Type Safety: C++ I/O is type-safe; the compiler checks that the data type matches the variable receiving it (unlike printf format specifiers).

Reading and Writing Data (cin and cout)

1. cout (Console Output)

  • Represents the standard output stream (monitor).
  • Uses the Insertion Operator (<<).
  • Can chain multiple outputs.

2. cin (Console Input)

  • Represents the standard input stream (keyboard).
  • Uses the Extraction Operator (>>).
  • Skips whitespace (spaces, newlines, tabs) by default.

Example:

CPP
#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: "; // Writing to screen
    cin >> age;                 // Reading from keyboard
    cout << "You are " << age << " years old."; 
    return 0;
}

Manipulator Functions

Manipulators are helper functions used to format the output stream. They are found in <iostream> and <iomanip>.

  1. endl: Inserts a new line and flushes the buffer (similar to \n).
  2. setw(n): Sets the field width to n characters (right-aligned by default).
  3. setprecision(n): Sets the number of digits displayed for floating-point numbers.
  4. fixed: Forces floating-point notation (prevents scientific notation).

CPP
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    cout << setw(10) << "Rank" << setw(10) << "Score" << endl;
    cout << setw(10) << 1 << setw(10) << 95.5 << endl;
    return 0;
}


3. Functions in C++

Inline Functions

An inline function is a request to the compiler to replace the function call with the actual code of the function at compile time.

  • Benefit: Eliminates function call overhead (stack push/pop), increasing execution speed for small functions.
  • Syntax: Use the keyword inline.
  • Limitations: Compilers may ignore the inline request if the function contains loops, switch statements, static variables, or recursion.

CPP
inline int square(int x) {
    return x * x;
}

Functions with Default Arguments

C++ allows functions to have optional parameters. If the caller does not provide a value, the default value is used.

  • Rule: Default arguments must be assigned from right to left in the function declaration.

CPP
// Valid: z defaults to 10, y to 20
int sum(int x, int y = 20, int z = 10); 

// Invalid: Cannot skip middle arguments
// int sum(int x = 5, int y, int z = 10); 

Function Overloading

Function overloading is a feature of compile-time polymorphism where two or more functions can have the same name but different parameter lists.

  • Differentiated by:
    1. Number of arguments.
    2. Type of arguments.
  • Note: Return type alone is not sufficient to distinguish overloaded functions.

Scope Rules

  • Local Scope: Variables declared inside a function/block are accessible only there.
  • Global Scope: Variables declared outside all functions are accessible everywhere (unless shadowed).
  • Block Scope: Variables declared inside { } (like in an if or for loop) exist only within that block.
  • Scope Resolution Operator (::): Used to access a global variable when a local variable has the same name.

Recursion

Recursion occurs when a function calls itself.

  • Base Case: The condition that stops the recursion to prevent infinite loops.
  • Recursive Step: The logic where the function calls itself with modified arguments.
  • Member Function Recursion: Class member functions can also be recursive.

4. Parameter Passing Techniques

Reference Variables

A reference variable is an alias (another name) for an existing variable.

  • Syntax: DataType &refName = originalVar;
  • Constraint: Must be initialized at the time of declaration.

Call by Value vs. Address vs. Reference

Feature Call by Value Call by Address (Pointer) Call by Reference
Method Passes a copy of the actual parameter. Passes the address of the actual parameter. Passes the reference (alias) of the actual parameter.
Effect on Original Changes in the function do not affect the original variable. Changes do affect the original variable. Changes do affect the original variable.
Memory Separate memory allocated for formal parameters. Pointer variables hold addresses. No new memory; shares memory with the argument.
Syntax void func(int x) void func(int *x) void func(int &x)
Call Syntax func(a); func(&a); func(a);

5. Classes and Objects

A Class is a user-defined data type that binds data and functions together. An Object is an instance of a class.

Creating Classes

CPP
class Student {
    // Access Specifier
    private:
        int id;            // Data Member
    public:
        void setData(int x); // Member Function
};

Class Objects

Objects are variables of the class type.

CPP
Student s1; // s1 is an object of class Student

Accessing Class Members

Members are accessed using the dot operator (.).

CPP
s1.setData(101);

Access Specifiers

  1. Private: Members are accessible only within the class. This is the default access specifier.
  2. Public: Members are accessible from outside the class.
  3. Protected: Used in inheritance (accessible in the class and derived classes).

Comparing Structures, Unions, Enums, and Classes

Feature Structure (struct) Union (union) Enumeration (enum) Class (class)
Default Access Public Public N/A Private
Memory Sum of size of all members. Size of the largest member (shared memory). Size of an integer. Sum of size of all data members.
Purpose Grouping diverse data. Memory optimization. Named integer constants. Data abstraction & encapsulation (OOP).
Functions Can have functions (in C++). Can have functions. Cannot have functions. Designed to hold data & functions.

6. Member Functions: Inline and Non-inline

Member functions can be defined in two places:

1. Inside the Class Definition (Implicit Inline)
When a function is defined inside the class body, it is treated as an inline function automatically.

CPP
class Box {
public:
    void print() { cout << "Hello"; } // Inline
};

2. Outside the Class Definition (Non-Inline)
Defined using the Scope Resolution Operator (::). This is preferred for complex functions.

CPP
class Box {
public:
    void print(); // Declaration
};

// Definition
void Box::print() {
    cout << "Hello";
}


7. Static Members

The static keyword creates members that belong to the class rather than a specific object.

Static Data Members

  • Shared Memory: Only one copy of the static variable exists, shared by all objects of that class.
  • Initialization: Must be defined outside the class using the scope resolution operator. Default value is 0.
  • Usage: Counters, shared configuration.

CPP
class Test {
    static int count; // Declaration
public:
    Test() { count++; }
};
int Test::count = 0; // Definition

Static Member Functions

  • Access: Can only access static data members and other static member functions. They cannot access non-static data (no this pointer).
  • Calling: Called using the class name: ClassName::functionName().

8. Friend Concept

Encapsulation hides data, but sometimes external functions need access to private members. The friend keyword allows this.

Friend Function

A non-member function that is granted permission to access private and protected members of a class.

  • Declaration: Inside the class with friend keyword.
  • Definition: Outside the class (does not use ClassName::).
  • Call: Called like a normal function, passing the object as an argument.

CPP
class Box {
    int width;
public:
    friend void printWidth(Box b); // Friend declaration
};

void printWidth(Box b) {
    // Accessing private member 'width'
    cout << b.width; 
}

Friend Class

If Class B is a friend of Class A, then all member functions of Class B can access the private members of Class A.

CPP
class A {
    int privateData;
    friend class B; // Class B is a friend
};

class B {
public:
    void showA(A& aObj) {
        cout << aObj.privateData; // Allowed
    }
};

  • Note: Friendship is not mutual (if A is friend of B, B is not automatically friend of A) and not inherited.