Basics of C++ Programming
Open in the Padhaiko app2.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.
// 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;
}- Header Files (
#include <iostream>): Provide declarations for standard streams (cin,cout,cerr) and utilities (<iomanip>,<cmath>,<string>). - Comments: Single-line (
// ...) and multi-line (/* ... */) comments are stripped before compilation. - Console I/O:
cout << expr(insertion operator) writes to standard output;cin >> var(extraction operator) reads whitespace-delimited input from standard input. main()Function: Every hosted C++ program begins execution atint main()and returns0to the operating system on normal termination.
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).
C++ Tokens
A token is the smallest individual lexical unit in a C++ program recognized by the compiler. C++ has six categories of tokens:
- Keywords: Reserved words with fixed meaning (
int,class,const,return,virtual,template,namespace,new,delete). Cannot be used as variable names. - 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. - Constants / Literals: Fixed values written directly in source code (
42,3.14,'A',"Institute of Engineering",true). - Strings: Sequences of characters enclosed in double quotes (
"Hello"), stored with a terminating null character'\0'in C-style literals. - Operators: Symbols that perform operations on operands (arithmetic
+,-,*,/,%; relational; logical; bitwise; scope::; member.,->). - 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:
int count;declarescount(uninitialized local variables hold indeterminate garbage values).int count = 0;,int count(0);, orint count{0};declare and initializecount.
An expression combines variables, literals, and operators to yield a value (and possibly side effects). Key precedence levels from highest to lowest:
- Scope resolution
:: - Postfix
++,--,(),[],.,-> - Unary prefix
++,--,!,~,+,-,*(dereference),&(address-of),sizeof - Multiplicative
*,/,%, then additive+,- - Shift
<<,>>, relational<,<=,>,>=, equality==,!= - Bitwise AND
&, XOR^, bitwise OR, logical AND&&, logical OR - 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.
| Type | Typical Size | Approximate Range | Purpose |
|---|---|---|---|
bool | 1 byte | false (0) or true (1) | Boolean truth values |
char | 1 byte | -128 to 127 (signed) or 0 to 255 | Single ASCII character or small byte |
short int | 2 bytes | -32,768 to 32,767 | Small integers |
int | 4 bytes | -2,147,483,648 to 2,147,483,647 | Standard integer arithmetic |
long long int | 8 bytes | about -9.22e18 to 9.22e18 | Large integer calculations |
float | 4 bytes | ~6–7 decimal digits precision | Single-precision floating point |
double | 8 bytes | ~15 decimal digits precision | Double-precision floating point |
void | — | No values | Empty return type or generic pointer void * |
- Type Modifiers:
signed,unsigned,short, andlongalter the sign and bit width of integer/character types. - Derived Types: Arrays, functions, pointers, and references.
- User-Defined Types:
struct,union,enum,class, andtypedef/usingaliases.
2.5 Type conversion and casting
Converting a value from one type to another happens either automatically or explicitly:
- 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 adoubleto aninttruncates the fractional part. - Explicit Type Casting: Requested by the programmer:
- C-style cast:
(double)a / bor function-styledouble(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-style cast:
| Cast Operator | Primary 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.
- Syntax:
const double PI = 3.14159;(must be initialized at declaration). - Advantages over
#define PI 3.14159:constobeys C++ scope rules, participates in type checking, and is visible in debuggers, whereas#defineis a blind text substitution by the preprocessor.
2.7 Reference variables
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.
| Aspect | Reference Variable (int &r = x) | Pointer Variable (int *p = &x) |
|---|---|---|
| Initialization | Must be initialized when declared | Can be uninitialized or set to nullptr |
| Rebinding | Always bound to the same original variable | Can be reassigned to point to other objects |
| Null Value | Cannot be null | Can hold nullptr |
| Access Syntax | Used directly (r = 20;) | Requires dereferencing (*p = 20;) |
| Memory Address | Shares the exact address of the target | Occupies its own storage holding an address |
2.8 Conditions and looping
C++ provides selection and iteration statements for flow control:
- Branching (
if,else if,else,switch,?:):if / else if / elsehandles arbitrary boolean conditions.switch (expr)dispatches on an integral orenumexpression usingcaselabels andbreak;(withoutbreak, execution falls through to the nextcase).- Ternary operator
cond ? expr1 : expr2returns a value inline.
- Looping (
for,while,do-while):for (init; cond; update): entry-controlled, ideal when iteration count is known.while (cond): entry-controlled, checks condition before each pass (0 or more iterations).do { ... } while (cond);: exit-controlled, guarantees at least 1 execution of the loop body.break;exits the innermost loop/switch immediately;continue;skips to the next iteration.
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.
#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;
}- Scope Resolution Operator (
::): Accesses a global variable shadowed by a local variable (::x), a namespace member (std::cout), or a class member defined outside the class (ClassName::method). - Unnamed Namespace:
namespace { int helper = 1; }restricts internal linkage to the current translation unit (modern replacement for file-scopestatic).
2.10 Functions
A function breaks a task into a reusable block with a declaration (prototype), definition, and call:
- Prototype:
double power(double base, int exp);informs the compiler of parameter types and return type before first use. - Call by Value: Copies argument values into parameters; changes inside the function do not affect the caller's variables.
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.
- Return type alone cannot distinguish overloaded functions (e.g.,
int f(int);anddouble f(int);cause a compile error). - The compiler resolves the call at compile time (compile-time polymorphism) using name mangling to encode parameter types into unique linker symbols.
- Ambiguity Caution: Combining overloaded functions with default arguments or implicit numeric promotions (e.g.,
void f(float)vsvoid f(double)called withf(3)orf(3.5)where3.5isdouble) can produce an ambiguous-call error.
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 int cube(int x) {
return x * x * x;
}- Unlike
#define CUBE(x) ((x)*(x)*(x)), aninlinefunction performs type checking and evaluates arguments only once (socube(++i)works safely). inlineis a request, not a command: compilers ignore it for large functions, recursive functions, loops/switches inside the body, or when taking the function's address.
2.10.3 Default arguments
A function can specify default values for trailing parameters in its declaration (prototype):
double simpleInterest(double p, double t, double r = 0.08);- Rule: Default values must be provided from right to left without gaps.
void f(int a = 1, int b)is invalid. - Defaults should be placed in the prototype (not repeated in the separate definition).
2.10.4 Pass by reference and return by reference
- Pass by Reference: Parameters declared as references (
void swapVals(int &a, int &b)) bind directly to the caller's arguments without copying, letting the function modify original variables cleanly without pointer syntax. Useconst T &to avoid copying large objects while guaranteeing read-only access. - Return by Reference: A function returning
T &returns an lvalue (alias to an existing variable) instead of a temporary copy, so the call itself can appear on the left-hand side of=:
#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
- Arrays: Contiguous fixed-size sequences of same-type elements (
int a[5] = {10, 20, 30, 40, 50};, 0-indexed). In expressions, an array name decays to a pointer to its first element (aequals&a[0]). - Pointers: Variables storing memory addresses (
int *p = a;). Pointer arithmetic scales automatically bysizeof(T):p + 2advances by2 * sizeof(int)bytes (*(a + i)equalsa[i]). - Strings:
- C-style strings: Null-terminated character arrays (
char name[20] = "Pokhara";), manipulated with<cstring>functions (strlen,strcpy,strcmp). Risk buffer overflow if bounds are ignored. - C++
std::string(<string>): Dynamic, bounds-safe string class supporting+concatenation,==comparison,.length(), andgetline(cin, s).
- C-style strings: Null-terminated character arrays (
2.12 Structure and unions
struct: Groups heterogeneous members where every member has its own distinct memory location. Total size is at least the sum of member sizes (plus alignment padding). In C++, astructcan also contain member functions and constructors; its only language difference fromclassis thatstructmembers default topublic, whereasclassmembers default toprivate.union: Groups members that share the exact same memory space. Only one member can hold a meaningful value at a time; the size of aunionequals the size of its largest member (subject to alignment).
| Aspect | Structure (struct) | Union (union) |
|---|---|---|
| Memory Allocation | Separate memory for every member | All members share one overlapping memory block |
| Size | Sum of member sizes (+ alignment padding) | Size of the largest single member (+ alignment) |
| Active Members | All members store independent values simultaneously | Only one member is valid at any time |
| Use Case | Records (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:
- Unscoped
enum:enum Color { RED, GREEN = 5, BLUE };assignsRED = 0,GREEN = 5,BLUE = 6. Enumerators leak into the enclosing scope and implicitly convert toint. - Scoped
enum class(C++11+):enum class Traffic { Red, Yellow, Green };scopes names underTraffic::Redand prevents accidental implicit conversion toint.
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.
#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;
}| Aspect | new / delete (C++) | malloc() / free() (C) |
|---|---|---|
| Nature | C++ operators | C library functions (<cstdlib>) |
| Return Type | Typed pointer (int *) — no cast needed | Generic void * — requires cast in C++ |
| Size Calculation | Automatic (new int[10]) | Manual (10 * sizeof(int)) |
| Constructors / Destructors | Automatically invokes constructor / destructor | Does not call constructors or destructors |
| Failure Behaviour | Throws std::bad_alloc (unless nothrow) | Returns NULL / nullptr |
Worked Examples
1
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).
#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-argumentarea(double)->3.14159 * 49 = 153.93791(printed with default 6 significant digits as153.938).area(5.0, 4.0)matches 2-argumentarea(double, double)->5 * 4 = 20.area(3.0, 4.0, 5.0)matches 3-argumentarea(double, double, double):s = 6.0,sqrt(6 * 3 * 2 * 1) = sqrt(36) = 6.
The three overloaded area definitions resolve at compile time by argument count, outputting:
Circle: 153.938Rectangle: 20Triangle: 6
2
Trace the following C++ program demonstrating dynamic memory allocation, pointer arithmetic, default arguments, and pass by reference, and determine its exact output.
#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):
datainitially holds{3, 5, 2, 10}.scaleAndAccumulate(data, 4, sum)uses the defaultfactor = 2, resetstotal(which aliasessumby reference) to0, doubles each element to{6, 10, 4, 20}, and accumulates6 + 10 + 4 + 20 = 40.- First line prints
4 40.
Second Call (factor = 3 explicitly passed):
datacurrently holds{6, 10, 4, 20}.- Multiplying each element by
3produces{18, 30, 12, 60}, andsumis updated via reference to18 + 30 + 12 + 60 = 120. - Second line prints
12 120. Finallydelete[] data;frees the heap array cleanly.
Line 1: 4 40 Line 2: 12 120
Exercises
Exercises — Basics of C++ Programming
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:
- Default Arguments: Defining
void show(int a)alongsidevoid show(int a, int b = 0)makesshow(5)ambiguous because both signatures match one argument. - Implicit Type Conversions: Defining
void print(float x)andvoid print(double x)makesprint(5)(anintliteral) ambiguous because convertinginttofloatandinttodoublehave equal standard-conversion rank.
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.
Compare inline functions with #define macros. List three situations where a compiler may ignore the inline request.
Inline Functions vs. Macros:
- Processing Stage:
#definemacros are expanded blindly by the preprocessor before compilation;inlinefunctions are compiled by the C++ compiler. - Type Safety:
inlinefunctions enforce full parameter and return type checking; macros do not. - Side Effects: Calling a macro
SQ(++x)expands to(++x)*(++x), incrementingxtwice; aninlinefunction evaluates++xonly once before entering the body.
When the Compiler Ignores inline:
- The function contains loops (
for,while,do-while) or complexswitch/gotostatements. - The function is recursive.
- The function is too large, or its address is taken through a function pointer.
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.
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:
#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),xaliasesa(12) andyaliasesb(19). - Since
12 >= 19is false,x = 0setsa = 0, andreturn y;returns a reference tob. += 10adds10directly tob, yieldingb = 19 + 10 = 29.
After pickLarger(a, b) += 10;, a = 0 and b = 29. Output: a = 0, b = 29.
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 = 13bytes per element. An array of10Records takes10 * 13 = 130bytes. - In
union Value, all members overlap in the same memory block, so its size equals the largest member (double=8bytes). An array of10Values takes10 * 8 = 80bytes.
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).
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.
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)asilently 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 stripconstor cast unrelated pointers, and is easy to spot in code reviews:
int total = 7, count = 2;
double avg = static_cast<double>(total) / count; // 3.5 (safe, explicit)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.