OOP · ENCT 151

Ch 2. Basics of C++ Programming

5 hours · 7 marks

2.1 C++ Program Structure

#include <iostream>      // preprocessor directive
using namespace std;      // namespace declaration

int main() {               // entry point of every program
    cout << "Hello World"; // statement
    return 0;               // return status to OS
}

A typical C++ program has: preprocessor directives, namespace declarations, global declarations (optional), the main() function (mandatory, execution starts here), and other user-defined functions/classes.

2.2 Character Set and Tokens

Character set: letters (A–Z, a–z), digits (0–9), special symbols (+ - * / = ; , . etc.), and white space.

Tokens are the smallest individual units of a program. Types of tokens:

2.3 Variable Declaration and Expression

A variable must be declared with a type before use: int age = 21;. C++ allows declaration anywhere before first use (unlike old C which required declarations at the top of a block).

An expression combines variables, constants and operators to produce a value, e.g. a + b * c. Expressions can be arithmetic, relational, logical, or assignment expressions.

2.4 Data Types

CategoryTypesTypical size
Fundamentalint, char, float, double, bool, void4, 1, 4, 8, 1 bytes
Modifierssigned, unsigned, short, longmodifies range/size
Derivedarray, pointer, function, referencedepends on base type
User-definedstruct, union, class, enum, typedefdepends on members

2.5 Type Conversion and Casting

2.6 User Defined Constant — const

const float PI = 3.1416;   // value cannot change after initialization
const int SIZE = 10;
// PI = 3.14;  -> compile error

const is preferred over the C preprocessor macro #define because it is type-checked by the compiler and obeys scope rules.

2.7 Reference Variables

A reference is an alias (another name) for an existing variable, declared with &. It must be initialized when declared and cannot be reseated afterward.

int a = 10;
int &ref = a;   // ref is an alias for a
ref = 20;        // a becomes 20 too
cout << a;       // prints 20

References are commonly used for pass-by-reference function arguments and for returning objects by reference, avoiding costly copies.

2.8 Conditions and Looping

for (int i = 1; i <= 5; i++) cout << i << " ";
int i = 0;
do { cout << i; i++; } while (i < 3);

2.9 Namespace Scope

A namespace groups related identifiers under a name to avoid naming collisions between libraries/modules.

namespace MyLib {
    int value = 5;
    void show() { cout << value; }
}
int main() {
    MyLib::show();        // scope resolution operator ::
    using namespace MyLib; // brings all names into scope
}

std is the standard namespace containing cout, cin, string, etc.

2.10 Functions

A function is a named block of code that performs a task and can be called repeatedly. Syntax: returnType name(parameters) { body }.

2.10.1 Function Overloading

Multiple functions with the same name but different parameter lists (number/type of parameters) in the same scope. Resolved at compile time (static polymorphism).

int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }

2.10.2 Inline Function

Requests the compiler to substitute the function's code directly at the call site instead of a normal function call, avoiding call overhead — best for small, frequently used functions.

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

2.10.3 Default Arguments

A parameter can have a default value used when the caller omits an argument. Default arguments must be specified from right to left.

void greet(string name, string msg = "Hello") {
    cout << msg << ", " << name;
}
greet("Ram");           // uses default msg
greet("Ram", "Hi");     // overrides default

2.10.4 Pass by Reference and Return by Reference

void increment(int &x) { x++; }   // pass by reference — modifies caller's variable
int &getElement(int arr[], int i) { return arr[i]; } // return by reference

Pass-by-reference avoids copying (efficient for large objects) and allows the function to modify the caller's variable directly, unlike pass-by-value.

2.11 Array, Pointer and String

2.12 Structure and Unions

Structure (struct)Union (union)
Each member gets its own memory; total size = sum of membersAll members share the same memory location; size = size of largest member
All members can hold values simultaneouslyOnly one member holds a valid value at a time
struct Point { int x, y; };
union Data { int i; float f; char c; };

2.13 Enumeration

enum defines a set of named integer constants, improving code readability.

enum Day { SUN, MON, TUE, WED, THU, FRI, SAT }; // SUN=0, MON=1 ...
Day today = WED;
enum Level { LOW = 1, MEDIUM = 5, HIGH = 10 };   // custom values

2.14 Dynamic Memory Allocation

Memory allocated at run time on the heap, using new and released using delete (C++), as opposed to C's malloc()/free().

int *p = new int;         // single variable
*p = 10;
delete p;                  // free memory

int *arr = new int[5];    // array
delete[] arr;              // free array memory (note the [])

Failing to delete allocated memory causes a memory leak.

Most Probable Questions

Q1. What is function overloading? Write a program to overload a function area() for circle, rectangle, and triangle. 5 marks
Definition: multiple functions with the same name but different parameter lists.
#include <iostream>
using namespace std;
float area(float r) { return 3.1416 * r * r; }             // circle
float area(float l, float b) { return l * b; }              // rectangle
float area(float b, float h, bool tri) { return 0.5*b*h; }  // triangle
int main() {
    cout << area(5) << endl;
    cout << area(4, 6) << endl;
    cout << area(4, 6, true) << endl;
}
Q2. Differentiate between call by value and call by reference with example. 4 marks
Call by value copies the argument's value into the parameter — changes inside the function do not affect the original variable. Call by reference passes an alias to the original variable — changes inside the function directly affect the caller's variable.
void byValue(int x) { x = 100; }         // caller's variable unaffected
void byRef(int &x) { x = 100; }          // caller's variable changed
int main() {
    int a = 5;
    byValue(a); cout << a; // 5
    byRef(a);   cout << a; // 100
}
Q3. What is an inline function? What are its advantages and limitations? 4 marks
An inline function is expanded at the call site instead of being called normally, avoiding function-call overhead (stack push/pop). Advantages: faster execution for small functions, avoids call overhead. Limitations: increases code size (code bloat) if overused, the compiler may ignore the inline request for large/recursive functions, not suitable for functions with loops or large bodies.
Q4. What is dynamic memory allocation? Explain new and delete operators with example. 5 marks
Dynamic memory allocation means allocating memory at run time from the heap rather than at compile time. new allocates memory and returns a pointer to it; delete releases memory back to the system. See code in section 2.14. Emphasize: always match every new with a delete, and every new[] with delete[], to avoid memory leaks.
Q5. Differentiate between structure and union. 4 marks
See table in section 2.12: struct allocates separate memory per member (size = sum of all members); union shares one memory block among all members (size = largest member), so only one member is valid at a time.
Q6. What are default arguments? Write the rule governing their use with an example. 4 marks
Default arguments are values automatically used for parameters the caller does not supply. Rule: once a parameter is given a default value, all parameters to its right must also have default values (defaults are assigned right-to-left). Example in section 2.10.3.
Q7. What is a reference variable? How is it different from a pointer? 4 marks
A reference is an alias for an existing variable, must be initialized at declaration, and cannot be changed to refer to another variable afterward. A pointer stores an address, can be reassigned to point elsewhere, can be null, and requires explicit dereferencing (*p). References use simpler syntax and are commonly used for function parameters.
Q8. Write a C++ program using enum to represent days of the week and print whether a given day is a weekend. 5 marks
#include <iostream>
using namespace std;
enum Day { SUN, MON, TUE, WED, THU, FRI, SAT };
int main() {
    Day d = SAT;
    if (d == SUN || d == SAT) cout << "Weekend";
    else cout << "Weekday";
}
Q9. What is type casting? Explain the different C++ style cast operators. 4 marks
Type casting converts a value from one data type to another. C++ provides four safer, explicit cast operators: static_cast (general-purpose conversions checked at compile time), dynamic_cast (safe downcasting in polymorphic class hierarchies, checked at run time), const_cast (adds/removes const/volatile), reinterpret_cast (low-level reinterpretation of bit patterns, e.g. pointer type conversions).
Q10. What are tokens in C++? List and briefly explain their types. 4 marks
Tokens are the smallest meaningful elements of a program: keywords, identifiers, literals/constants, punctuators, and operators (see section 2.2 for definitions and examples of each).
← Chapter 1 Next: Chapter 3 — Objects and Classes →