PadhaikoAll subjects

Basics of C++ Programming

Object Oriented Programming (ENCT 151)

Open in the Padhaiko app

2.1 C++ Program structure

A standard C++ program is organized into distinct sections that tell the preprocessor, compiler, and linker how to build an executable.

Anatomy of a Basic C++ ProgramC++
// 1. Documentation / Comments
#include <iostream>     // 2. Preprocessor directive (header inclusion)
using namespace std;    // 3. Namespace directive

// 4. Global declarations / function prototypes / class definitions
int square(int n);

int main() {            // 5. Execution entry point
    int x = 5;
    cout << "Square = " << square(x) << endl;
    return 0;           // Exit status 0 -> success
}

// 6. User-defined function definitions
int square(int n) {
    return n * n;
}

2.2 Character set and tokens

The C++ character set includes uppercase/lowercase letters (A–Z, a–z), digits (0–9), special symbols (+ - * / = ( ) { } [ ] < > ; : , . & ^ % ! ~ ? # ' " \ _), and whitespace characters (space, tab, newline).

Definition

C++ Tokens

A token is the smallest individual lexical unit in a C++ program recognized by the compiler. C++ has six categories of tokens:

  1. Keywords: Reserved words with fixed meaning (int, class, const, return, virtual, template, namespace, new, delete). Cannot be used as variable names.
  2. Identifiers: User-defined names for variables, functions, classes, and namespaces. Rules: must start with a letter or underscore _, followed by letters, digits, or _; case-sensitive; cannot match a keyword.
  3. Constants / Literals: Fixed values written directly in source code (42, 3.14, 'A', "Institute of Engineering", true).
  4. Strings: Sequences of characters enclosed in double quotes ("Hello"), stored with a terminating null character '\0' in C-style literals.
  5. Operators: Symbols that perform operations on operands (arithmetic +, -, *, /, %; relational; logical; bitwise; scope ::; member ., ->).
  6. Punctuators / Separators: Structural symbols such as ;, ,, (), {}, [], :.

2.3 Variable declaration and expression

A variable declaration introduces a name and a data type to the compiler; initialization assigns its starting value at the moment of creation:

An expression combines variables, literals, and operators to yield a value (and possibly side effects). Key precedence levels from highest to lowest:

  1. Scope resolution ::
  2. Postfix ++, --, (), [], ., ->
  3. Unary prefix ++, --, !, ~, +, -, * (dereference), & (address-of), sizeof
  4. Multiplicative *, /, %, then additive +, -
  5. Shift <<, >>, relational <, <=, >, >=, equality ==, !=
  6. Bitwise AND &, XOR ^, bitwise OR, logical AND &&, logical OR
  7. Ternary ?:, assignment =, +=, *=, and comma ,

2.4 Data types

C++ is a statically and strongly typed language: every variable has a known type at compile time.

Fundamental Data Types in C++ (Typical 64-bit LP64/LLP64 Systems)
TypeTypical SizeApproximate RangePurpose
bool1 bytefalse (0) or true (1)Boolean truth values
char1 byte-128 to 127 (signed) or 0 to 255Single ASCII character or small byte
short int2 bytes-32,768 to 32,767Small integers
int4 bytes-2,147,483,648 to 2,147,483,647Standard integer arithmetic
long long int8 bytesabout -9.22e18 to 9.22e18Large integer calculations
float4 bytes~6–7 decimal digits precisionSingle-precision floating point
double8 bytes~15 decimal digits precisionDouble-precision floating point
void—No valuesEmpty return type or generic pointer void *

2.5 Type conversion and casting

Converting a value from one type to another happens either automatically or explicitly:

  1. Implicit Type Conversion (Coercion / Promotion): Performed automatically by the compiler when operands of mixed types appear in an expression. Smaller types promote toward larger/floating types (bool/char/short -> int -> unsigned int -> long -> float -> double) to avoid data loss, though assigning a double to an int truncates the fractional part.
  2. Explicit Type Casting: Requested by the programmer:
    • C-style cast: (double)a / b or function-style double(a) / b.
    • C++ named cast (static_cast): static_cast<double>(a) / b. Checked at compile time and clearly searchable in code, making it preferred in modern C++.
C++ Named Cast Operators
Cast OperatorPrimary Purpose
static_cast<T>(expr)Standard well-defined conversions (numeric casts, upcasts, void pointer)
const_cast<T>(expr)Adds or removes const / volatile qualifiers
reinterpret_cast<T>(expr)Low-level bit reinterpretation between unrelated pointer/integer types
dynamic_cast<T>(expr)Safe run-time checked downcasting in polymorphic class hierarchies

2.6 User defined constant const

The const keyword declares an object whose value cannot be modified after initialization.


2.7 Reference variables

Definition

Reference Variable

A reference variable is an alias (another name) for an existing variable. It is declared using & in the type declaration: int x = 10; int &ref = x;. Any operation on ref directly reads or modifies x.

AspectReference Variable (int &r = x)Pointer Variable (int *p = &x)
InitializationMust be initialized when declaredCan be uninitialized or set to nullptr
RebindingAlways bound to the same original variableCan be reassigned to point to other objects
Null ValueCannot be nullCan hold nullptr
Access SyntaxUsed directly (r = 20;)Requires dereferencing (*p = 20;)
Memory AddressShares the exact address of the targetOccupies its own storage holding an address

2.8 Conditions and looping

C++ provides selection and iteration statements for flow control:


2.9 Namespace scope

In large programs combining multiple libraries, identical identifiers (like print() or Node) can collide. A namespace creates a named declarative region to isolate identifiers.

Namespaces and Scope ResolutionC++
#include <iostream>
using namespace std;

namespace Physics {
    const double g = 9.81;
    void show() { cout << "Physics g = " << g << endl; }
}

namespace Graphics {
    const double g = 2.2; // gamma
    void show() { cout << "Graphics gamma = " << g << endl; }
}

int main() {
    Physics::show();    // Explicit qualification using ::
    Graphics::show();
    using Physics::g;   // Selective using-declaration
    cout << g << endl;
    return 0;
}

2.10 Functions

A function breaks a task into a reusable block with a declaration (prototype), definition, and call:

2.10.1 Function overloading

Function overloading allows two or more functions in the same scope to share the same name provided their parameter lists differ in number, types, or sequence of parameters.

2.10.2 Inline function

When a tiny function is called inside a tight loop, pushing arguments, jumping, and returning incurs call overhead. Marking a function inline requests that the compiler substitute the function's body directly at each call site:

Inline Function SyntaxC++
inline int cube(int x) {
    return x * x * x;
}

2.10.3 Default arguments

A function can specify default values for trailing parameters in its declaration (prototype):

2.10.4 Pass by reference and return by reference

Pass by Reference and Return by ReferenceC++
#include <iostream>
using namespace std;

int &larger(int &a, int &b) {
    return (a > b) ? a : b;
}

int main() {
    int x = 10, y = 25;
    larger(x, y) = 99; // Modifies y directly because larger returns int&
    cout << "x = " << x << ", y = " << y << endl;
    return 0;
}

2.11 Array, pointer and string


2.12 Structure and unions

AspectStructure (struct)Union (union)
Memory AllocationSeparate memory for every memberAll members share one overlapping memory block
SizeSum of member sizes (+ alignment padding)Size of the largest single member (+ alignment)
Active MembersAll members store independent values simultaneouslyOnly one member is valid at any time
Use CaseRecords (Student, Point)Memory-constrained variants / hardware registers

2.13 Enumeration

An enumeration (enum) defines a user-defined type consisting of named integral constants, improving readability over magic numbers:


2.14 Dynamic memory allocation

Stack variables have fixed compile-time sizes and die when their scope ends. Dynamic memory allocation allocates memory from the heap (free store) at run time using new and releases it with delete.

Dynamic Allocation of Single Object and ArrayC++
#include <iostream>
using namespace std;

int main() {
    int *p = new int(42);        // Allocates 1 int initialized to 42
    int n = 4;
    int *arr = new int[n]{1, 2, 3, 4}; // Dynamic array of 4 ints

    int sum = *p;
    for (int i = 0; i < n; ++i) sum += arr[i];
    cout << "Total = " << sum << endl;

    delete p;      // Free single object
    delete[] arr;  // Always pair new[] with delete[]
    p = nullptr;
    arr = nullptr; // Prevents dangling pointer
    return 0;
}
Aspectnew / delete (C++)malloc() / free() (C)
NatureC++ operatorsC library functions (<cstdlib>)
Return TypeTyped pointer (int *) — no cast neededGeneric void * — requires cast in C++
Size CalculationAutomatic (new int[10])Manual (10 * sizeof(int))
Constructors / DestructorsAutomatically invokes constructor / destructorDoes not call constructors or destructors
Failure BehaviourThrows std::bad_alloc (unless nothrow)Returns NULL / nullptr

Worked Examples

Example 1

1 (6 marks)

Write a C++ program that uses function overloading to compute the area of a circle (double radius), a rectangle (double length, double breadth), and a triangle (double a, double b, double c using Heron's formula), and trace the output for radius = 7, length = 5, breadth = 4, and sides 3, 4, 5.

Designing Overloaded area() Functions: All three functions share the name area but have different parameter signatures: (double), (double, double), and (double, double, double).

Overloaded area() FunctionsC++
#include <iostream>
#include <cmath>
using namespace std;

double area(double r) {
    return 3.14159 * r * r;
}

double area(double l, double b) {
    return l * b;
}

double area(double a, double b, double c) {
    double s = (a + b + c) / 2.0;
    return sqrt(s * (s - a) * (s - b) * (s - c));
}

int main() {
    cout << "Circle: " << area(7.0) << endl;
    cout << "Rectangle: " << area(5.0, 4.0) << endl;
    cout << "Triangle: " << area(3.0, 4.0, 5.0) << endl;
    return 0;
}

Tracing Each Overloaded Call:

  • area(7.0) matches 1-argument area(double) -> 3.14159 * 49 = 153.93791 (printed with default 6 significant digits as 153.938).
  • area(5.0, 4.0) matches 2-argument area(double, double) -> 5 * 4 = 20.
  • area(3.0, 4.0, 5.0) matches 3-argument area(double, double, double): s = 6.0, sqrt(6 * 3 * 2 * 1) = sqrt(36) = 6.
Answer:

The three overloaded area definitions resolve at compile time by argument count, outputting:

  • Circle: 153.938
  • Rectangle: 20
  • Triangle: 6
Example 2

2 (5 marks)

Trace the following C++ program demonstrating dynamic memory allocation, pointer arithmetic, default arguments, and pass by reference, and determine its exact output.

Dynamic Array, Pointers, and ReferencesC++
#include <iostream>
using namespace std;

void scaleAndAccumulate(int *arr, int size, int &total, int factor = 2) {
    total = 0;
    for (int i = 0; i < size; ++i) {
        *(arr + i) *= factor;
        total += *(arr + i);
    }
}

int main() {
    int n = 4;
    int *data = new int[n]{3, 5, 2, 10};
    int sum = 999;

    scaleAndAccumulate(data, n, sum);
    cout << data[2] << " " << sum << endl;

    scaleAndAccumulate(data, n, sum, 3);
    cout << data[2] << " " << sum << endl;

    delete[] data;
    data = nullptr;
    return 0;
}

First Call (factor defaults to 2):

  • data initially holds {3, 5, 2, 10}.
  • scaleAndAccumulate(data, 4, sum) uses the default factor = 2, resets total (which aliases sum by reference) to 0, doubles each element to {6, 10, 4, 20}, and accumulates 6 + 10 + 4 + 20 = 40.
  • First line prints 4 40.

Second Call (factor = 3 explicitly passed):

  • data currently holds {6, 10, 4, 20}.
  • Multiplying each element by 3 produces {18, 30, 12, 60}, and sum is updated via reference to 18 + 30 + 12 + 60 = 120.
  • Second line prints 12 120. Finally delete[] data; frees the heap array cleanly.
Answer:

Line 1: 4 40 Line 2: 12 120


Exercises

Exercises — Basics of C++ Programming

Question 1

What is function overloading in C++? Explain with an example how the compiler resolves overloaded calls, and mention two situations that cause ambiguity in function overloading.

Definition and Resolution: Function overloading lets multiple functions in the same scope share a name as long as their parameter lists differ in number, types, or order of parameters. The compiler picks the best match at compile time (exact match -> promotion -> standard conversion) and uses name mangling to give each overload a distinct linker symbol.

Two Causes of Ambiguity:

  1. Default Arguments: Defining void show(int a) alongside void show(int a, int b = 0) makes show(5) ambiguous because both signatures match one argument.
  2. Implicit Type Conversions: Defining void print(float x) and void print(double x) makes print(5) (an int literal) ambiguous because converting int to float and int to double have equal standard-conversion rank.
Answer:

Function overloading defines multiple functions with the same name but distinct parameter lists, resolved at compile time via name mangling. Ambiguity arises when default arguments overlap another overload's arity, or when implicit conversions (like int to float vs double) yield equally ranked matches.

Question 2

Compare inline functions with #define macros. List three situations where a compiler may ignore the inline request.

Inline Functions vs. Macros:

  1. Processing Stage: #define macros are expanded blindly by the preprocessor before compilation; inline functions are compiled by the C++ compiler.
  2. Type Safety: inline functions enforce full parameter and return type checking; macros do not.
  3. Side Effects: Calling a macro SQ(++x) expands to (++x)*(++x), incrementing x twice; an inline function evaluates ++x only once before entering the body.

When the Compiler Ignores inline:

  1. The function contains loops (for, while, do-while) or complex switch / goto statements.
  2. The function is recursive.
  3. The function is too large, or its address is taken through a function pointer.
Answer:

inline functions are type-checked, scoped, and evaluate arguments once, unlike text-substituted #define macros. Compilers typically ignore inline for recursive functions, functions containing loops/switches, or large functions / functions accessed via pointer.

Question 3

Write a C++ function using pass by reference and return by reference that compares two integers, sets the smaller one to 0, and increments the larger one by 10 through the returned reference. Trace its execution for initial values a = 12, b = 19.

Implementation: Pass int &x, int &y so modifications inside pickLarger directly alter the caller's variables, and return int & to alias the larger variable:

Pass and Return by ReferenceC++
#include <iostream>
using namespace std;

int &pickLarger(int &x, int &y) {
    if (x >= y) {
        y = 0;
        return x;
    } else {
        x = 0;
        return y;
    }
}

int main() {
    int a = 12, b = 19;
    pickLarger(a, b) += 10;
    cout << "a = " << a << ", b = " << b << endl;
    return 0;
}

Trace for a = 12, b = 19:

  • Inside pickLarger(a, b), x aliases a (12) and y aliases b (19).
  • Since 12 >= 19 is false, x = 0 sets a = 0, and return y; returns a reference to b.
  • += 10 adds 10 directly to b, yielding b = 19 + 10 = 29.
Answer:

After pickLarger(a, b) += 10;, a = 0 and b = 29. Output: a = 0, b = 29.

Question 4

A struct Record holds { int id; double score; char grade; } while a union Value holds { int id; double score; char grade; }. Assuming int = 4 bytes, double = 8 bytes, char = 1 byte, and no alignment padding, compute the minimum memory required for an array of 10 Records versus an array of 10 Values. Explain why new[] must always be paired with delete[].

Memory Calculation (No Padding):

  • In struct Record, every member has separate storage: 4 + 8 + 1 = 13 bytes per element. An array of 10 Records takes 10 * 13 = 130 bytes.
  • In union Value, all members overlap in the same memory block, so its size equals the largest member (double = 8 bytes). An array of 10 Values takes 10 * 8 = 80 bytes.

Pairing new[] with delete[]: When new T[N] allocates an array, the runtime stores the element count N (often just before the returned block) so delete[] knows to invoke the destructor N times and free the whole array. Using plain delete on an array allocated with new[] causes undefined behaviour (only one destructor runs or heap metadata is corrupted).

Answer:

An array of 10 Record structures takes 130 bytes, whereas 10 Value unions take 80 bytes. new[] must always be paired with delete[] so every element's destructor runs and the heap allocator frees the array cleanly without undefined behaviour.

Question 5

Explain the purpose of namespaces in C++, and differentiate between static_cast and a C-style cast with a short code example.

Purpose of Namespaces: Namespaces partition the global scope into named regions (namespace Audio { ... }, namespace Video { ... }), preventing name collisions when integrating multiple libraries that define identical class or function names. Members are accessed via Namespace::identifier or imported selectively with using.

static_cast vs. C-Style Cast:

  • A C-style cast (double)a silently attempts several dangerous casts (const_cast, static_cast, reinterpret_cast) without distinguishing intent.
  • static_cast<double>(a) performs only well-defined compile-time conversions, refuses to strip const or cast unrelated pointers, and is easy to spot in code reviews:
Integer Division Cast ComparisonC++
int total = 7, count = 2;
double avg = static_cast<double>(total) / count; // 3.5 (safe, explicit)
Answer:

Namespaces prevent global identifier collisions across libraries via scoped regions accessed with ::. static_cast<T>(expr) performs compile-time checked, well-defined conversions without accidentally stripping const or reinterpreting unrelated pointers like C-style casts can.

← Introduction to Object Oriented ProgrammingObjects and Classes →