Unit 4 - Notes
Unit 4: Fundamentals of Programming Languages
1. C/C++/Java Interview Questions Overview
This section provides a comparative analysis of C, C++, and Java, focusing on the theoretical nuances often addressed in technical interviews.
1.1 Comparative Analysis
- C (Procedural): A low-level, structure-oriented language. It focuses on functions and manual memory management. It does not support OOP concepts inherently.
- C++ (Hybrid): An extension of C that introduces Object-Oriented Programming (OOP). It supports both procedural and object-oriented paradigms. It allows manual memory management but provides abstractions (constructors/destructors).
- Java (Pure Object-Oriented): Designed for platform independence ("Write Once, Run Anywhere"). It runs on the Java Virtual Machine (JVM). It removes pointers (for security) and handles memory automatically via Garbage Collection.
1.2 Common Interview Themes
- Platform Dependence:
- C/C++: Platform dependent. Compiled code (binary) targets a specific machine architecture (e.g., x86 Windows).
- Java: Platform independent. The compiler produces Bytecode (
.class), which is interpreted by the JVM on any OS.
- Pointers:
- C/C++: Supports explicit pointer arithmetic and manipulation.
- Java: Does not support explicit pointers. References are used to access objects, but memory addresses cannot be manipulated directly.
- Multiple Inheritance:
- C++: Supports multiple inheritance (a class can inherit from multiple classes).
- Java: Does not support multiple inheritance of classes (to avoid the "Diamond Problem") but achieves similar functionality through Interfaces.
2. Pointers and Storage
Pointers are variables that store the memory address of another variable. They are fundamental to C and C++ for dynamic memory allocation and efficient array handling.
2.1 Pointer Fundamentals (C/C++)
- Declaration:
int *ptr;(Declares a pointer to an integer). - Initialization:
int val = 10; ptr = &val;(Stores the address ofvalinptr). - Dereferencing:
*ptraccesses the value stored at the address (returns 10).
Key Concepts:
- Null Pointer: A pointer assigned
NULL(ornullptrin modern C++) indicating it points to nothing. - *Void Pointer (`void`):** A generic pointer that can point to any data type but cannot be dereferenced without casting.
- Pointer Arithmetic: Incrementing a pointer (
ptr++) moves the address bysizeof(type). For anint(4 bytes), the address increases by 4.
2.2 Storage Classes
Storage classes define the scope (visibility), lifetime, and initial value of variables.
| Storage Class | Keyword | Storage Location | Default Value | Scope | Lifetime |
|---|---|---|---|---|---|
| Automatic | auto |
Stack | Garbage | Local (Block) | End of block |
| Register | register |
CPU Register | Garbage | Local (Block) | End of block |
| Static | static |
Data Segment | Zero | Local (Block)* | Program runtime |
| External | extern |
Data Segment | Zero | Global | Program runtime |
- Note on Static: A static variable inside a function retains its value between function calls.
- Note on Register: This is a request to the compiler; the compiler may ignore it if registers are full.
3. Introduction to Object-Oriented Programming (OOP)
OOP is a programming paradigm based on the concept of "objects," which can contain data (attributes) and code (methods).
3.1 Procedural vs. OOP
- Procedural: Focuses on steps/functions. Data is often global and insecure. Difficult to maintain for large systems.
- OOP: Focuses on objects combining data and behavior. Data is secure (encapsulated). Easier to maintain and scale.
3.2 The Four Pillars of OOP
- Encapsulation: Wrapping data (variables) and code (methods) together as a single unit (Class). It hides internal details and restricts access using access specifiers.
- Abstraction: Hiding complex implementation details and showing only the essential features of the object. (Example: Using a
sort()function without knowing the sorting algorithm). - Inheritance: A mechanism where a new class (Child/Derived) acquires the properties and behaviors of an existing class (Parent/Base). It promotes code reusability.
- Polymorphism: The ability of a message or function to take more than one form.
- Compile-time: Function Overloading / Operator Overloading.
- Run-time: Function Overriding (Virtual functions).
4. Classes
A Class is a user-defined data type that acts as a blueprint for creating objects.
4.1 Anatomy of a Class
- Attributes (Data Members): Variables holding the state of the object.
- Methods (Member Functions): Functions defining the behavior of the object.
4.2 Access Specifiers
These control the visibility of class members:
- Public: Accessible from anywhere outside the class.
- Private: Accessible only within the class (and by
friendfunctions in C++). This ensures Encapsulation. - Protected: Accessible within the class and by derived classes (used in Inheritance).
4.3 Constructors and Destructors
- Constructor: A special method invoked automatically when an object is created. Used to initialize objects. It has the same name as the class and no return type.
- Destructor: Invoked when an object is destroyed (goes out of scope or explicitly deleted). Used to release resources. Syntax:
~ClassName(). (Note: Java has no explicit destructor, it usesfinalize()traditionally, though now deprecated in favor ofCleaner/try-with-resources).
Example (C++ Syntax):
class Car {
private:
int speed; // Encapsulated data
public:
// Constructor
Car() { speed = 0; }
// Method
void accelerate() { speed += 10; }
};
5. Techniques of Parameter Passing and Binding
This topic covers how data is transferred between functions and how function calls are mapped to memory addresses.
5.1 Parameter Passing Mechanisms
A. Call by Value
- A copy of the actual parameter’s value is passed to the function.
- Changes made inside the function do not affect the original variable.
- Memory: Creates duplicate variables on the stack.
- Used in: C, C++, Java (Java is strictly pass-by-value, passing the value of the reference for objects).
B. Call by Address (Pointer)
- The address (pointer) of the variable is passed.
- The function accesses the variable via dereferencing.
- Changes do affect the original variable.
- Used in: C, C++.
C. Call by Reference
- An alias (reference) to the actual variable is passed.
- No new memory copy is created; the parameter is the original variable.
- Syntax:
void func(int &x) { ... } - Used in: C++ (specifically).
5.2 Binding (Linking Function Calls)
Binding is the process of connecting a function call to the actual code block to be executed.
A. Static Binding (Early Binding)
- The compiler determines which function to call at compile time.
- Examples: Normal function calls, Function Overloading.
- Performance: Faster execution.
B. Dynamic Binding (Late Binding)
- The exact function to be called is determined at runtime based on the type of object.
- Requirement: Requires Virtual Functions (in C++) or method overriding.
- Mechanism: Uses a v-table (Virtual Table) lookup.
- Example: A base class pointer pointing to a derived class object calls the derived class's method.
6. Memory Handling in OOP Languages
Memory management is critical for performance and preventing crashes. It involves allocation (reserving memory) and deallocation (freeing memory).
6.1 Memory Segments
- Code Segment: Stores compiled binary instructions.
- Data Segment: Stores global and static variables.
- Stack: Stores local variables and function call frames (LIFO structure). Management is automatic.
- Heap: Stores dynamic memory (objects created at runtime). Management is manual (C++) or automatic (Java).
6.2 Manual Memory Management (C++)
- Allocation: Uses the
newoperator. Returns a pointer to the allocated memory.int* p = new int;
- Deallocation: Uses the
deleteoperator.delete p;
- Risks:
- Memory Leak: Failing to
deletememory results in occupied RAM that is never freed. - Dangling Pointer: A pointer pointing to a memory location that has already been deleted.
- Memory Leak: Failing to
6.3 Automatic Memory Management (Java)
- Allocation: Uses the
newkeyword. Objects are always created on the Heap. - Garbage Collection (GC): A background process (part of JVM) that automatically identifies and frees objects that are no longer referenced by any part of the program.
- Mark-and-Sweep: The common algorithm where the GC "marks" reachable objects and "sweeps" (deletes) the unreachable ones.
6.4 Stack vs. Heap
| Feature | Stack | Heap |
|---|---|---|
| Size | Small, fixed size. | Large, flexible size. |
| Speed | Very fast access. | Slower access (requires pointers). |
| Lifetime | Scope-based (Automatic). | Program runtime (or until deleted). |
| Allocation | Contiguous blocks. | Random blocks (can lead to fragmentation). |