0% found this document useful (0 votes)
16 views94 pages

C++ Basics: Identifiers, Keywords, Constants

This document serves as an introduction to C++ programming, covering fundamental concepts such as identifiers, keywords, constants, variable declaration, statements, expressions, and input/output operations. It also details C++ operators, including arithmetic, relational, logical, assignment, increment/decrement, bitwise, conditional, and sizeof operators. The content is structured into sections that provide definitions, examples, and best practices for each topic.

Uploaded by

kalpitjain0204
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views94 pages

C++ Basics: Identifiers, Keywords, Constants

This document serves as an introduction to C++ programming, covering fundamental concepts such as identifiers, keywords, constants, variable declaration, statements, expressions, and input/output operations. It also details C++ operators, including arithmetic, relational, logical, assignment, increment/decrement, bitwise, conditional, and sizeof operators. The content is structured into sections that provide definitions, examples, and best practices for each topic.

Uploaded by

kalpitjain0204
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT 2: Introduction to C++

Table of Contents
1. Basic Elements of C++
2. C++ Operators and Expressions
3. Control Structures
4. Classes and Objects
5. Advanced Class Features
6. Memory Management

1. BASIC ELEMENTS OF C++


1.1 Identifiers
Definition: Names given to variables, functions, classes, arrays, or any user-defined items in a program.

Rules for Identifiers:

Must begin with a letter (A-Z, a-z) or underscore (_)


Can contain letters, digits (0-9), and underscores
Cannot use C++ keywords
Case-sensitive (age and Age are different)
No spaces or special characters allowed
Cannot start with a digit

Valid Identifiers:

cpp

student_name
age
_total
myClass
temperature2

Invalid Identifiers:

cpp
2ndValue // Starts with digit
my-name // Contains hyphen
int // Keyword
my name // Contains space
@value // Contains special character

Naming Conventions (Best Practices):

cpp

// Variables: camelCase or snake_case


int studentAge;
int student_age;

// Constants: UPPER_CASE
const int MAX_SIZE = 100;

// Classes: PascalCase
class StudentRecord;

// Functions: camelCase
void calculateTotal();

1.2 Keywords (Reserved Words)


Definition: Predefined words in C++ that have special meaning and cannot be used as identifiers.

C++ Keywords (Total: 95+):

cpp
// Data Types
int, float, double, char, bool, void, long, short, signed, unsigned

// Control Flow
if, else, switch, case, default, break, continue, return, goto

// Loops
for, while, do

// Class Related
class, struct, union, enum, public, private, protected, friend

// Object Oriented
new, delete, this, virtual, override, final

// Function Related
inline, static, extern, const, volatile

// Exception Handling
try, catch, throw

// Type Casting
static_cast, dynamic_cast, const_cast, reinterpret_cast

// Others
sizeof, typedef, namespace, using, template, typename
auto, nullptr, constexpr, decltype

Important Points:

Keywords are always lowercase (except NULL, TRUE, FALSE in older code)
Cannot be redefined or used as variable names
Each keyword has a specific purpose in the language

1.3 Constants
Definition: Fixed values that do not change during program execution.

A. Literal Constants

Integer Literals:

cpp
int decimal = 100; // Decimal
int octal = 0144; // Octal (prefix 0)
int hexadecimal = 0x64; // Hexadecimal (prefix 0x)
int binary = 0b1100100; // Binary (prefix 0b, C++14)

long longValue = 100L; // Long suffix


unsigned int uValue = 100U; // Unsigned suffix

Floating-Point Literals:

cpp

float pi = 3.14f; // Float suffix


double value = 3.14159; // Double (default)
double scientific = 1.5e3; // Scientific notation (1500.0)
long double precise = 3.14159L; // Long double

Character Literals:

cpp

char letter = 'A'; // Single character


char newline = '\n'; // Escape sequence
char tab = '\t';
char backslash = '\\';
char quote = '\'';

String Literals:

cpp

"Hello World" // C-style string


"Line 1\nLine 2" // With escape sequences
"Path: C:\\Users" // Escaped backslash

Boolean Literals:

cpp
bool isTrue = true;
bool isFalse = false;

Escape Sequences:

cpp

\n // Newline
\t // Tab
\\ // Backslash
\' // Single quote
\" // Double quote
\0 // Null character
\r // Carriage return
\b // Backspace

B. Symbolic Constants

Using const Keyword:

cpp

const int MAX_STUDENTS = 50;


const double PI = 3.14159;
const char GRADE = 'A';

// Cannot be modified later


// MAX_STUDENTS = 60; // ERROR!

Using #define Preprocessor:

cpp
#define PI 3.14159
#define MAX 100
#define NEWLINE '\n'

// No type checking, textual replacement


double area = PI * radius * radius;

Using constexpr (C++11):

cpp

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


constexpr int value = square(5); // Evaluated at compile time

Comparison: const vs #define:

cpp

// const - Type safe, scoped, debugger friendly


const int MAX = 100;

// #define - No type checking, global, textual replacement


#define MAX 100

1.4 Variable Declaration


Definition: The process of defining a variable with its name and data type.

Syntax:

cpp

data_type variable_name;
data_type variable_name = initial_value;

Basic Declarations:

cpp
// Single variable
int age;
double salary;
char grade;

// Multiple variables of same type


int x, y, z;
float a, b, c;

// Declaration with initialization


int count = 0;
double price = 99.99;
char initial = 'A';
bool isActive = true;

// Multiple initialization
int a = 10, b = 20, c = 30;

Scope of Variables:

Local Variables:

cpp

void myFunction() {
int x = 10; // Local to myFunction
// Accessible only within this function
}

Global Variables:

cpp
int globalVar = 100; // Accessible everywhere

void function1() {
cout << globalVar; // Can access
}

void function2() {
globalVar = 200; // Can modify
}

Static Variables:

cpp

void counter() {
static int count = 0; // Initialized only once
count++;
cout << count;
}

counter(); // Output: 1
counter(); // Output: 2
counter(); // Output: 3

Auto Type Deduction (C++11):

cpp

auto x = 5; // x is int
auto y = 3.14; // y is double
auto name = "John"; // name is const char*
auto vec = vector<int>(); // vec is vector<int>

1.5 Statements and Expressions

Statements

Definition: A complete instruction that performs an action.

Types of Statements:

1. Expression Statement:
cpp

x = 10; // Assignment
y = x + 5; // Calculation
cout << "Hello"; // Function call
count++; // Increment

2. Compound Statement (Block):

cpp

{
int x = 10;
int y = 20;
int sum = x + y;
} // Variables x, y, sum destroyed here

3. Declaration Statement:

cpp

int age = 25;


double salary;

4. Null Statement:

cpp

; // Does nothing, just a semicolon

Expressions

Definition: A combination of variables, operators, and values that evaluates to a result.

Types of Expressions:

Arithmetic Expressions:
cpp

x+y
a*b+c
(a + b) / (c - d)

Relational Expressions:

cpp

x>y // true or false


age >= 18
score == 100

Logical Expressions:

cpp

(x > 5) && (y < 10)


(age >= 18) || (hasPermission)
!(isError)

Assignment Expressions:

cpp

x = 10 // Returns 10
y = (x = 5) // x becomes 5, y becomes 5
a = b = c = 0 // All become 0 (right to left)

Conditional Expression (Ternary):

cpp
result = (condition) ? value_if_true : value_if_false;

// Example
int max = (a > b) ? a : b;
string status = (age >= 18) ? "Adult" : "Minor";

1.6 Input and Output

Output using cout

Basic Syntax:

cpp

#include <iostream>
using namespace std;

cout << "text" << variable << expression;

Examples:

cpp

// Simple output
cout << "Hello World";

// Output variables
int age = 25;
cout << "Age: " << age;

// Multiple items
cout << "Name: " << name << ", Age: " << age;

// Newline
cout << "Line 1" << endl; // Using endl
cout << "Line 2\n"; // Using \n

// Chaining
cout << "a = " << a << ", b = " << b << ", c = " << c << endl;

Formatting Output:
cpp

#include <iomanip>

// Set width
cout << setw(10) << 123; // " 123"

// Set precision for floating point


cout << setprecision(2) << 3.14159; // 3.14
cout << fixed << setprecision(2) << 3.14159; // 3.14

// Alignment
cout << left << setw(10) << "Name";
cout << right << setw(10) << "Value";

// Fill character
cout << setfill('*') << setw(10) << 42; // "********42"

Input using cin

Basic Syntax:

cpp

#include <iostream>
using namespace std;

cin >> variable;

Examples:

cpp
int age;
cout << "Enter age: ";
cin >> age;

// Multiple inputs
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;

// String input (single word)


string name;
cout << "Enter name: ";
cin >> name; // Stops at whitespace

// String with spaces


string fullName;
cout << "Enter full name: ";
[Link](); // Clear buffer
getline(cin, fullName); // Reads entire line

// Character input
char grade;
cout << "Enter grade: ";
cin >> grade;

Input Buffer Management:

cpp
// Clear input buffer
[Link]();

// Clear buffer and discard all


[Link](numeric_limits<streamsize>::max(), '\n');

// Check for input failure


if ([Link]()) {
cout << "Invalid input!";
[Link](); // Clear error flags
[Link](numeric_limits<streamsize>::max(), '\n');
}

2. C++ OPERATORS AND TYPE CONVERSION


2.1 C++ Operators

A. Arithmetic Operators

Definition: Perform mathematical operations.

cpp

+ // Addition
- // Subtraction
* // Multiplication
/ // Division
% // Modulus (remainder)

// Examples
int a = 10, b = 3;
cout << a + b; // 13
cout << a - b; // 7
cout << a * b; // 30
cout << a / b; // 3 (integer division)
cout << a % b; // 1 (remainder)

double x = 10.0, y = 3.0;


cout << x / y; // 3.333... (floating division)

B. Relational Operators
Definition: Compare two values and return boolean result.

cpp

== // Equal to
!= // Not equal to
> // Greater than
< // Less than
>= // Greater than or equal to
<= // Less than or equal to

// Examples
int a = 10, b = 20;
cout << (a == b); // false (0)
cout << (a != b); // true (1)
cout << (a > b); // false
cout << (a < b); // true
cout << (a >= 10); // true
cout << (b <= 15); // false

C. Logical Operators

Definition: Combine multiple conditions.

cpp
&& // Logical AND
|| // Logical OR
! // Logical NOT

// Examples
bool a = true, b = false;

cout << (a && b); // false (both must be true)


cout << (a || b); // true (at least one true)
cout << (!a); // false (negation)

// Practical examples
int age = 25;
bool hasLicense = true;

if (age >= 18 && hasLicense) {


cout << "Can drive";
}

if (age < 18 || !hasLicense) {


cout << "Cannot drive";
}

D. Assignment Operators

Definition: Assign values to variables.

cpp
= // Simple assignment
+= // Add and assign
-= // Subtract and assign
*= // Multiply and assign
/= // Divide and assign
%= // Modulus and assign

// Examples
int x = 10;

x += 5; // x = x + 5; (x becomes 15)
x -= 3; // x = x - 3; (x becomes 12)
x *= 2; // x = x * 2; (x becomes 24)
x /= 4; // x = x / 4; (x becomes 6)
x %= 4; // x = x % 4; (x becomes 2)

E. Increment and Decrement Operators

Definition: Increase or decrease value by 1.

cpp

++ // Increment
-- // Decrement

// Pre-increment/decrement (++x, --x)


int x = 5;
int y = ++x; // x becomes 6, y is 6 (increment first)

// Post-increment/decrement (x++, x--)


int a = 5;
int b = a++; // b is 5, then a becomes 6 (use first, then increment)

// Examples
int i = 10;
cout << i++; // Prints 10, then i becomes 11
cout << ++i; // i becomes 12, then prints 12

int j = 10;
cout << j--; // Prints 10, then j becomes 9
cout << --j; // j becomes 8, then prints 8
F. Bitwise Operators

Definition: Perform operations on individual bits.

cpp

& // Bitwise AND


| // Bitwise OR
^ // Bitwise XOR
~ // Bitwise NOT
<< // Left shift
>> // Right shift

// Examples
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011

cout << (a & b); // 1 (0001)


cout << (a | b); // 7 (0111)
cout << (a ^ b); // 6 (0110)
cout << (~a); // -6 (inverts all bits)
cout << (a << 1); // 10 (1010) - multiply by 2
cout << (a >> 1); // 2 (0010) - divide by 2

G. Conditional (Ternary) Operator

Syntax:

cpp

condition ? expression_if_true : expression_if_false;

Examples:

cpp
int a = 10, b = 20;
int max = (a > b) ? a : b; // max = 20

string result = (age >= 18) ? "Adult" : "Minor";

// Nested ternary
int grade = (score >= 90) ? 1 :
(score >= 80) ? 2 :
(score >= 70) ? 3 : 4;

H. sizeof Operator

Definition: Returns size of data type or variable in bytes.

cpp

cout << sizeof(int); // 4 (typically)


cout << sizeof(char); // 1
cout << sizeof(double); // 8
cout << sizeof(float); // 4

int arr[10];
cout << sizeof(arr); // 40 (10 * 4)

string name = "John";


cout << sizeof(name); // Size of string object

I. Comma Operator

Definition: Evaluates multiple expressions, returns the last one.

cpp

int a = (x = 5, y = 10, x + y); // a = 15

for (int i = 0, j = 10; i < j; i++, j--) {


cout << i << " " << j << endl;
}

Operator Precedence Table (Highest to Lowest):


1. :: (scope)
2. () [] -> . (postfix ++ --)
3. ! ~ (prefix ++ --) + - * & sizeof (type)
4. */%
5. +-
6. << >>
7. < <= > >=
8. == !=
9. &
10. ^
11. |
12. &&
13. ||
14. ?:
15. = += -= *= /= %= &= ^= |= <<= >>=
16. ,

2.2 Type Conversion


Definition: Converting one data type to another.

A. Implicit Type Conversion (Automatic)

Definition: Compiler automatically converts smaller data type to larger.

cpp
// Integer to Float
int a = 10;
float b = a; // Automatic conversion, b = 10.0

// Char to Int
char c = 'A';
int x = c; // x = 65 (ASCII value)

// Float to Double
float f = 3.14f;
double d = f; // Automatic widening

// In expressions
int i = 5;
double result = i / 2.0; // i converted to double, result = 2.5

Type Promotion Hierarchy:

char → short → int → unsigned int → long → unsigned long →


float → double → long double

Important Points:

cpp

// Loss of data in narrowing conversion


double d = 9.99;
int i = d; // i = 9 (decimal part lost)

// Mixed type arithmetic


int a = 5;
double b = 2.0;
auto result = a / b; // result is double (5.0 / 2.0 = 2.5)

// Integer division issue


int x = 5, y = 2;
double z = x / y; // z = 2.0 (integer division, then converted)
double w = (double)x / y; // w = 2.5 (correct)
B. Explicit Type Conversion (Casting)

1. C-Style Casting:

cpp

(type) expression

// Examples
double pi = 3.14159;
int x = (int)pi; // x = 3

float a = 5.5;
int b = (int)(a + 2.5); // b = 8

char ch = 'A';
int ascii = (int)ch; // ascii = 65

2. Function-Style Casting:

cpp

type(expression)

// Examples
int a = int(3.14); // a = 3
double d = double(10); // d = 10.0
char c = char(65); // c = 'A'

3. C++ Style Casting (Recommended):

static_cast (Compile-time casting):

cpp
double d = 3.14;
int i = static_cast<int>(d); // i = 3

int x = 10, y = 3;
double result = static_cast<double>(x) / y; // 3.333...

// Pointer casting
void* ptr = malloc(sizeof(int));
int* intPtr = static_cast<int*>(ptr);

dynamic_cast (Runtime type checking for polymorphism):

cpp

class Base { virtual void func() {} };


class Derived : public Base {};

Base* basePtr = new Derived();


Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
if (derivedPtr) {
// Successful cast
}

const_cast (Remove const qualifier):

cpp

const int x = 10;


int* ptr = const_cast<int*>(&x);
*ptr = 20; // Dangerous! Undefined behavior

reinterpret_cast (Low-level pointer/reference reinterpretation):

cpp

int x = 65;
char* ch = reinterpret_cast<char*>(&x);

Comparison of Casting Methods:


cpp

// C-style: Simple but unsafe


int a = (int)3.14;

// static_cast: Type-safe, compile-time check


int b = static_cast<int>(3.14);

// Best practice: Use C++ style casts for clarity and safety

3. CONTROL STRUCTURES
3.1 Conditional Statements

A. if Statement

Syntax:

cpp

if (condition) {
// statements
}

Example:

cpp

int age = 20;

if (age >= 18) {


cout << "You are an adult";
}

// Without braces (single statement)


if (age >= 18)
cout << "Adult";

B. if-else Statement
Syntax:

cpp

if (condition) {
// statements if true
} else {
// statements if false
}

Example:

cpp

int marks = 75;

if (marks >= 50) {


cout << "Pass";
} else {
cout << "Fail";
}

C. if-else-if Ladder

Syntax:

cpp

if (condition1) {
// statements
} else if (condition2) {
// statements
} else if (condition3) {
// statements
} else {
// default statements
}

Example:
cpp

int score = 85;

if (score >= 90) {


cout << "Grade A";
} else if (score >= 80) {
cout << "Grade B";
} else if (score >= 70) {
cout << "Grade C";
} else if (score >= 60) {
cout << "Grade D";
} else {
cout << "Grade F";
}

D. Nested if Statement

Example:

cpp

int age = 20;


bool hasLicense = true;

if (age >= 18) {


if (hasLicense) {
cout << "Can drive";
} else {
cout << "Need license";
}
} else {
cout << "Too young to drive";
}

E. switch Statement

Syntax:

cpp
switch (expression) {
case constant1:
// statements
break;
case constant2:
// statements
break;
default:
// default statements
}

Example:

cpp
int day = 3;

switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
default:
cout << "Invalid day";
}

// Character switch
char grade = 'B';
switch (grade) {
case 'A':
cout << "Excellent";
break;
case 'B':
cout << "Good";
break;
case 'C':
cout << "Average";
break;
default:
cout << "Invalid grade";
}
// Fall-through behavior (without break)
int month = 2;
switch (month) {
case 12:
case 1:
case 2:
cout << "Winter";
break;
case 3:
case 4:
case 5:
cout << "Spring";
break;
}

3.2 Loop Statements

A. for Loop

Syntax:

cpp

for (initialization; condition; increment/decrement) {


// statements
}

Examples:

cpp
// Basic for loop
for (int i = 1; i <= 5; i++) {
cout << i << " "; // Output: 1 2 3 4 5
}

// Reverse loop
for (int i = 10; i >= 1; i--) {
cout << i << " ";
}

// Step by 2
for (int i = 0; i <= 10; i += 2) {
cout << i << " "; // 0 2 4 6 8 10
}

// Multiple variables
for (int i = 0, j = 10; i < j; i++, j--) {
cout << i << " " << j << endl;
}

// Infinite loop
for (;;) {
cout << "Infinite loop";
break; // Need break to exit
}

// Range-based for loop (C++11)


int arr[] = {1, 2, 3, 4, 5};
for (int x : arr) {
cout << x << " ";
}

vector<int> vec = {10, 20, 30};


for (int val : vec) {
cout << val << " ";
}

B. while Loop

Syntax:

cpp
while (condition) {
// statements
}

Examples:

cpp

// Basic while loop


int i = 1;
while (i <= 5) {
cout << i << " ";
i++;
}

// Sum of numbers
int sum = 0, n = 1;
while (n <= 10) {
sum += n;
n++;
}
cout << "Sum = " << sum;

// User input validation


int num;
cout << "Enter positive number: ";
cin >> num;
while (num <= 0) {
cout << "Invalid! Enter positive number: ";
cin >> num;
}

// Infinite loop
while (true) {
cout << "Running...";
break; // Need break to exit
}

C. do-while Loop

Syntax:
cpp

do {
// statements
} while (condition);

Examples:

cpp
// Basic do-while
int i = 1;
do {
cout << i << " ";
i++;
} while (i <= 5);

// Menu-driven program
int choice;
do {
cout << "\n1. Add\n2. Subtract\n3. Exit\n";
cout << "Enter choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Addition";
break;
case 2:
cout << "Subtraction";
break;
case 3:
cout << "Exiting...";
break;
default:
cout << "Invalid choice";
}
} while (choice != 3);

// Executes at least once (key difference from while)


int x = 10;
do {
cout << x; // Prints 10 even though condition is false
} while (x < 5);

D. Nested Loops

Examples:

cpp
// Nested for loops - Multiplication table
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
cout << i * j << "\t";
}
cout << endl;
}

// Pattern printing - Right triangle


for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
// Output:
// *
// * *
// * * *
// * * * *
// * * * * *

// 2D array traversal
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}

3.3 Break and Continue Statements

A. break Statement

Definition: Terminates the loop or switch statement immediately.

Examples:

cpp
// Exit loop when condition met
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Loop stops at i = 5
}
cout << i << " "; // Output: 1 2 3 4
}

// Search in array
int arr[] = {10, 20, 30, 40, 50};
int target = 30;
bool found = false;

for (int i = 0; i < 5; i++) {


if (arr[i] == target) {
found = true;
cout << "Found at index " << i;
break; // Stop searching
}
}

// break in nested loops (only exits inner loop)


for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
break; // Only exits inner loop
}
cout << i << "," << j << " ";
}
cout << endl;
}

B. continue Statement

Definition: Skips the rest of the current iteration and continues with the next iteration.

Examples:

cpp
// Skip even numbers
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip rest of loop body
}
cout << i << " "; // Output: 1 3 5 7 9
}

// Skip negative numbers


int numbers[] = {10, -5, 20, -3, 30};
for (int i = 0; i < 5; i++) {
if (numbers[i] < 0) {
continue; // Skip negative
}
cout << numbers[i] << " "; // Output: 10 20 30
}

// Continue in while loop


int i = 0;
while (i < 10) {
i++;
if (i % 3 == 0) {
continue; // Skip multiples of 3
}
cout << i << " ";
}

C. goto Statement (Not Recommended)

Syntax:

cpp

goto label;
// ...
label:
// statements

Example:

cpp
int i = 0;
start:
cout << i << " ";
i++;
if (i < 5)
goto start; // Jump back to start

// Breaking nested loops


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
goto end; // Exit both loops
}
cout << i << "," << j << " ";
}
}
end:
cout << "Done";

// Note: goto is generally avoided in modern C++

4. CLASSES AND OBJECTS


4.1 Classes

Definition: A class is a user-defined data type that encapsulates data members and member functions into a single unit.

Syntax:

cpp
class ClassName {
private:
// Private data members and functions

protected:
// Protected members

public:
// Public interface
// Constructor
// Member functions
// Destructor
};

Basic Class Example:

cpp

class Student {
private:
int rollNo;
string name;
float marks;

public:
// Member function to set data
void setData(int r, string n, float m) {
rollNo = r;
name = n;
marks = m;
}

// Member function to display data


void display() {
cout << "Roll No: " << rollNo << endl;
cout << "Name: " << name << endl;
cout << "Marks: " << marks << endl;
}
};

Access Specifiers:

1. private:
Accessible only within the class
Default access level for class members
Provides data hiding

cpp

class Example {
private:
int privateVar; // Cannot access outside class

void privateFunction() {
// Only accessible within class
}
};

2. public:

Accessible from anywhere


Forms the interface of the class

cpp

class Example {
public:
int publicVar; // Accessible everywhere

void publicFunction() {
// Can be called from anywhere
}
};

3. protected:

Accessible within the class and derived classes


Used in inheritance

cpp
class Base {
protected:
int protectedVar; // Accessible in derived classes
};

class Derived : public Base {


public:
void accessProtected() {
protectedVar = 10; // OK, can access
}
};

Complete Class Example:

cpp
class Rectangle {
private:
double length;
double width;

public:
// Setter methods
void setLength(double l) {
if (l > 0)
length = l;
else
cout << "Invalid length";
}

void setWidth(double w) {
if (w > 0)
width = w;
else
cout << "Invalid width";
}

// Getter methods
double getLength() {
return length;
}

double getWidth() {
return width;
}

// Calculate area
double area() {
return length * width;
}

// Calculate perimeter
double perimeter() {
return 2 * (length + width);
}
};
4.2 Member Functions

Definition: Functions defined inside a class that operate on class data members.

A. Member Function Inside Class

cpp

class Circle {
private:
double radius;

public:
// Function defined inside class
void setRadius(double r) {
radius = r;
}

double getArea() {
return 3.14159 * radius * radius;
}
};

B. Member Function Outside Class

Syntax: ReturnType ClassName::functionName(parameters)

cpp
class Circle {
private:
double radius;

public:
void setRadius(double r); // Declaration
double getArea(); // Declaration
};

// Definition outside class


void Circle::setRadius(double r) {
radius = r;
}

double Circle::getArea() {
return 3.14159 * radius * radius;
}

C. Types of Member Functions

1. Accessor (Getter) Functions:

cpp

class Student {
private:
int age;

public:
int getAge() const { // const means doesn't modify data
return age;
}
};

2. Mutator (Setter) Functions:

cpp
class Student {
private:
int age;

public:
void setAge(int a) {
if (a > 0 && a < 100)
age = a;
}
};

3. Utility/Helper Functions:

cpp

class Calculator {
public:
int add(int a, int b) {
return a + b;
}

int multiply(int a, int b) {


return a * b;
}
};

4. const Member Functions:

cpp
class Point {
private:
int x, y;

public:
// const function - cannot modify data members
void display() const {
cout << "(" << x << ", " << y << ")";
// x = 10; // ERROR! Cannot modify in const function
}

int getX() const { return x; }


int getY() const { return y; }
};

4.3 Objects
Definition: An instance of a class. It is a real-world entity that occupies memory.

Object Declaration Syntax:

cpp

ClassName objectName;

Creating and Using Objects:

cpp
class Car {
public:
string brand;
string model;
int year;

void displayInfo() {
cout << brand << " " << model << " (" << year << ")" << endl;
}
};

int main() {
// Creating objects
Car car1;
Car car2;

// Accessing members using dot operator


[Link] = "Toyota";
[Link] = "Camry";
[Link] = 2023;

[Link] = "Honda";
[Link] = "Civic";
[Link] = 2022;

// Calling member functions


[Link](); // Toyota Camry (2023)
[Link](); // Honda Civic (2022)

return 0;
}

Multiple Objects:

cpp
class Student {
private:
int id;
string name;

public:
void setData(int i, string n) {
id = i;
name = n;
}

void display() {
cout << id << " - " << name << endl;
}
};

int main() {
Student s1, s2, s3; // Three objects

[Link](101, "Alice");
[Link](102, "Bob");
[Link](103, "Charlie");

[Link]();
[Link]();
[Link]();

return 0;
}

4.4 Arrays of Class Objects


Definition: An array where each element is an object of a class.

Syntax:

cpp

ClassName arrayName[size];

Example 1: Basic Array of Objects:


cpp

class Employee {
private:
int id;
string name;
float salary;

public:
void input() {
cout << "Enter ID, Name, Salary: ";
cin >> id >> name >> salary;
}

void display() {
cout << id << "\t" << name << "\t" << salary << endl;
}
};

int main() {
Employee emp[3]; // Array of 3 Employee objects

// Input data for all employees


for (int i = 0; i < 3; i++) {
cout << "Employee " << i + 1 << ":\n";
emp[i].input();
}

// Display all employees


cout << "\nEmployee Details:\n";
for (int i = 0; i < 3; i++) {
emp[i].display();
}

return 0;
}

Example 2: Array Initialization:

cpp
class Point {
public:
int x, y;

Point() : x(0), y(0) {} // Default constructor

Point(int a, int b) : x(a), y(b) {} // Parameterized constructor

void display() {
cout << "(" << x << ", " << y << ")" << endl;
}
};

int main() {
// Array with initialization
Point points[4] = {
Point(1, 2),
Point(3, 4),
Point(5, 6),
Point(7, 8)
};

for (int i = 0; i < 4; i++) {


points[i].display();
}

return 0;
}

Example 3: Student Records System:

cpp
class Student {
private:
int rollNo;
string name;
float marks[5];
float total;
float average;

public:
void input() {
cout << "Enter Roll No: ";
cin >> rollNo;
cout << "Enter Name: ";
cin >> name;

total = 0;
cout << "Enter 5 subject marks:\n";
for (int i = 0; i < 5; i++) {
cout << "Subject " << i + 1 << ": ";
cin >> marks[i];
total += marks[i];
}
average = total / 5;
}

void display() {
cout << rollNo << "\t" << name << "\t"
<< total << "\t" << average << endl;
}

float getAverage() {
return average;
}
};

int main() {
int n;
cout << "Enter number of students: ";
cin >> n;

Student students[n]; // Array of n students

// Input all students


for (int i = 0; i < n; i++) {
cout << "\nStudent " << i + 1 << ":\n";
students[i].input();
}

// Display all students


cout << "\nRoll\tName\tTotal\tAverage\n";
for (int i = 0; i < n; i++) {
students[i].display();
}

// Find topper
int topperIndex = 0;
for (int i = 1; i < n; i++) {
if (students[i].getAverage() > students[topperIndex].getAverage()) {
topperIndex = i;
}
}

cout << "\nTopper:\n";


students[topperIndex].display();

return 0;
}

4.5 Pointers and Classes


Definition: Pointers can store the address of objects and access class members.

A. Pointer to Object

Syntax:

cpp

ClassName* pointerName;

Example:

cpp
class Box {
public:
int length, width, height;

int volume() {
return length * width * height;
}
};

int main() {
Box b1;
Box* ptr = &b1; // Pointer to object

// Access using arrow operator (->)


ptr->length = 10;
ptr->width = 5;
ptr->height = 3;

cout << "Volume: " << ptr->volume() << endl;

// Alternative: Using dereference


(*ptr).length = 20; // Same as ptr->length = 20

return 0;
}

B. Dynamic Object Creation

cpp
class Student {
private:
int id;
string name;

public:
void setData(int i, string n) {
id = i;
name = n;
}

void display() {
cout << id << " - " << name << endl;
}
};

int main() {
// Dynamic allocation using new
Student* ptr = new Student();

ptr->setData(101, "Alice");
ptr->display();

// Must delete to free memory


delete ptr;

return 0;
}

C. Array of Objects using Pointers

cpp
class Point {
public:
int x, y;

void set(int a, int b) {


x = a;
y = b;
}

void display() {
cout << "(" << x << ", " << y << ")" << endl;
}
};

int main() {
// Dynamic array of objects
int n = 5;
Point* arr = new Point[n];

// Initialize array
for (int i = 0; i < n; i++) {
arr[i].set(i, i * 2);
}

// Display array
for (int i = 0; i < n; i++) {
arr[i].display();
}

// Free memory
delete[] arr;

return 0;
}

D. this Pointer

Definition: A special pointer that points to the object which calls the member function.

cpp
class Example {
private:
int value;

public:
void setValue(int value) {
this->value = value; // Distinguish parameter from member
}

int getValue() {
return this->value;
}

// Returning object itself


Example& increment() {
this->value++;
return *this; // Return current object
}
};

int main() {
Example obj;
[Link](10);
cout << [Link]() << endl; // 10

// Chaining member functions


[Link]().increment().increment();
cout << [Link]() << endl; // 13

return 0;
}

Key Points about this Pointer:

Implicitly passed to every non-static member function


Points to the object that invoked the function
Used to access members when parameter names conflict
Used to return current object from member function
Cannot be modified (it's a const pointer)

4.6 Nested Classes


Definition: A class declared inside another class.

Syntax:
cpp

class Outer {
private:
int outerData;

class Inner { // Nested class


private:
int innerData;

public:
void display() {
cout << "Inner class";
}
};

public:
void outerFunction() {
Inner innerObj;
[Link]();
}
};

Example 1: Basic Nested Class:

cpp
class University {
private:
string name;

public:
University(string n) : name(n) {}

// Nested class
class Department {
private:
string deptName;
int students;

public:
Department(string dn, int s) : deptName(dn), students(s) {}

void display() {
cout << "Department: " << deptName << endl;
cout << "Students: " << students << endl;
}
};

void displayUniversity() {
cout << "University: " << name << endl;
}
};

int main() {
University univ("MIT");
[Link]();

// Creating nested class object


University::Department cs("Computer Science", 500);
[Link]();

return 0;
}

Example 2: Nested Class with Outer Class Access:

cpp
class Outer {
private:
int x;

public:
Outer(int val) : x(val) {}

class Inner {
public:
void display(Outer& obj) {
// Inner class can access private members of outer
cout << "Outer x = " << obj.x << endl;
}
};

void showInner() {
Inner innerObj;
[Link](*this);
}
};

int main() {
Outer outerObj(100);
[Link]();

return 0;
}

Use Cases for Nested Classes:

When inner class is closely related to outer class


For better encapsulation
To logically group classes
Helper classes that are only used within outer class

5. ADVANCED CLASS FEATURES


5.1 Constructors

Definition: Special member function automatically called when an object is created. Used to initialize object data.

Characteristics:

Same name as class


No return type (not even void)
Automatically invoked
Can be overloaded
Cannot be inherited

A. Default Constructor

Definition: Constructor with no parameters.

cpp

class Student {
private:
int id;
string name;

public:
// Default constructor
Student() {
id = 0;
name = "Unknown";
cout << "Default constructor called" << endl;
}

void display() {
cout << "ID: " << id << ", Name: " << name << endl;
}
};

int main() {
Student s1; // Default constructor called automatically
[Link]();

return 0;
}

B. Parameterized Constructor

Definition: Constructor with parameters to initialize object with specific values.

cpp
class Rectangle {
private:
int length, width;

public:
// Parameterized constructor
Rectangle(int l, int w) {
length = l;
width = w;
cout << "Parameterized constructor called" << endl;
}

int area() {
return length * width;
}
};

int main() {
Rectangle r1(10, 5); // Calls parameterized constructor
cout << "Area: " << [Link]() << endl;

return 0;
}

C. Constructor with Default Arguments

cpp
class Point {
private:
int x, y;

public:
// Constructor with default arguments
Point(int a = 0, int b = 0) {
x = a;
y = b;
}

void display() {
cout << "(" << x << ", " << y << ")" << endl;
}
};

int main() {
Point p1; // Uses defaults: (0, 0)
Point p2(5); // Uses: (5, 0)
Point p3(5, 10); // Uses: (5, 10)

[Link]();
[Link]();
[Link]();

return 0;
}

D. Copy Constructor

Definition: Creates a new object as a copy of an existing object.

Syntax:

cpp

ClassName(const ClassName& obj);

cpp
class Sample {
private:
int value;

public:
// Parameterized constructor
Sample(int v) {
value = v;
cout << "Parameterized constructor" << endl;
}

// Copy constructor
Sample(const Sample& obj) {
value = [Link];
cout << "Copy constructor" << endl;
}

void display() {
cout << "Value: " << value << endl;
}
};

int main() {
Sample s1(10); // Parameterized constructor
Sample s2 = s1; // Copy constructor
Sample s3(s1); // Copy constructor (alternative syntax)

[Link]();
[Link]();
[Link]();

return 0;
}

E. Constructor Initialization List

Syntax:

cpp
ClassName(parameters) : member1(value1), member2(value2) {
// Constructor body
}

cpp

class Person {
private:
string name;
int age;
const int id; // const member must be initialized in initialization list

public:
// Using initialization list
Person(string n, int a, int i) : name(n), age(a), id(i) {
cout << "Person object created" << endl;
}

void display() {
cout << "ID: " << id << ", Name: " << name
<< ", Age: " << age << endl;
}
};

int main() {
Person p1("Alice", 25, 101);
[Link]();

return 0;
}

F. Constructor Overloading

cpp
class Box {
private:
int length, width, height;

public:
// Constructor 1: No parameters
Box() {
length = width = height = 1;
}

// Constructor 2: One parameter (cube)


Box(int side) {
length = width = height = side;
}

// Constructor 3: Three parameters


Box(int l, int w, int h) {
length = l;
width = w;
height = h;
}

int volume() {
return length * width * height;
}
};

int main() {
Box b1; // Calls constructor 1
Box b2(5); // Calls constructor 2
Box b3(10, 5, 3); // Calls constructor 3

cout << [Link]() << endl; // 1


cout << [Link]() << endl; // 125
cout << [Link]() << endl; // 150

return 0;
}

5.2 Destructors
Definition: Special member function automatically called when an object is destroyed. Used to free resources.

Characteristics:
Same name as class with tilde (~) prefix
No return type, no parameters
Cannot be overloaded
Only one destructor per class
Automatically invoked when object goes out of scope

Syntax:

cpp

~ClassName() {
// Cleanup code
}

Example 1: Basic Destructor:

cpp

class Sample {
public:
Sample() {
cout << "Constructor called" << endl;
}

~Sample() {
cout << "Destructor called" << endl;
}
};

int main() {
Sample s1;
cout << "Inside main" << endl;
// Destructor called automatically when s1 goes out of scope
return 0;
}
// Output:
// Constructor called
// Inside main
// Destructor called

Example 2: Destructor with Resource Cleanup:


cpp

class DynamicArray {
private:
int* arr;
int size;

public:
// Constructor - allocates memory
DynamicArray(int s) {
size = s;
arr = new int[size];
cout << "Array of size " << size << " created" << endl;
}

// Destructor - frees memory


~DynamicArray() {
delete[] arr;
cout << "Array memory freed" << endl;
}

void set(int index, int value) {


if (index >= 0 && index < size)
arr[index] = value;
}

int get(int index) {


if (index >= 0 && index < size)
return arr[index];
return -1;
}
};

int main() {
DynamicArray da(5);
[Link](0, 10);
[Link](1, 20);
cout << [Link](0) << endl;
// Destructor automatically called, memory freed
return 0;
}

Example 3: Constructor and Destructor Order:


cpp

class Demo {
private:
int id;

public:
Demo(int i) : id(i) {
cout << "Constructor " << id << endl;
}

~Demo() {
cout << "Destructor " << id << endl;
}
};

int main() {
Demo d1(1);
Demo d2(2);
Demo d3(3);
cout << "End of main" << endl;
return 0;
}
// Output:
// Constructor 1
// Constructor 2
// Constructor 3
// End of main
// Destructor 3 (LIFO order)
// Destructor 2
// Destructor 1

5.3 Inline Member Functions


Definition: Functions whose code is expanded at the point of call instead of being called. Reduces function call
overhead.

Characteristics:

Defined using inline keyword or defined inside class


Suitable for small, frequently called functions
Compiler may ignore inline request for large functions
Increases code size but improves speed

A. Implicit Inline (Defined Inside Class)


cpp

class Circle {
private:
double radius;

public:
// Automatically inline
void setRadius(double r) {
radius = r;
}

double getArea() {
return 3.14159 * radius * radius;
}
};

B. Explicit Inline (Using inline Keyword)

cpp

class Rectangle {
private:
int length, width;

public:
void setDimensions(int l, int w);
inline int area(); // Explicitly inline
};

// Definition outside class


void Rectangle::setDimensions(int l, int w) {
length = l;
width = w;
}

inline int Rectangle::area() {


return length * width;
}
C. Inline vs Regular Functions

cpp

class Math {
public:
// Inline - good for small functions
inline int square(int x) {
return x * x;
}

// Not suitable for inline - large function


int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
};

When to Use Inline:

Small functions (1-3 lines)


Frequently called functions
Functions without loops or recursion
Accessor/getter functions

When NOT to Use Inline:

Large functions
Functions with loops, switch statements
Recursive functions
Virtual functions

5.4 Static Class Members

Definition: Members that belong to the class rather than any specific object.

A. Static Data Members

Characteristics:

Shared by all objects of the class


Only one copy exists regardless of number of objects
Must be defined outside the class
Accessed using class name or object

Syntax:
cpp

class ClassName {
private:
static dataType variableName;
public:
static void functionName();
};

// Definition outside class


dataType ClassName::variableName = value;

Example:

cpp
class Counter {
private:
static int count; // Static data member
int id;

public:
Counter() {
count++;
id = count;
}

void display() {
cout << "Object ID: " << id << endl;
cout << "Total objects: " << count << endl;
}

static int getCount() {


return count;
}
};

// Definition of static member


int Counter::count = 0;

int main() {
cout << "Initial count: " << Counter::getCount() << endl;

Counter c1, c2, c3;

[Link]();
[Link]();
[Link]();

cout << "Total objects created: " << Counter::getCount() << endl;

return 0;
}
// Output:
// Initial count: 0
// Object ID: 1
// Total objects: 3
// Object ID: 2
// Total objects: 3
// Object ID: 3
// Total objects: 3
// Total objects created: 3

B. Static Member Functions

Characteristics:

Can be called without creating object


Can only access static data members
Cannot access non-static members directly
No this pointer

Example:

cpp
class MathOperations {
private:
static const double PI;

public:
// Static member function
static double circleArea(double radius) {
return PI * radius * radius;
}

static double circleCircumference(double radius) {


return 2 * PI * radius;
}

static int add(int a, int b) {


return a + b;
}
};

const double MathOperations::PI = 3.14159;

int main() {
// Call without creating object
cout << "Area: " << MathOperations::circleArea(5.0) << endl;
cout << "Circumference: " << MathOperations::circleCircumference(5.0) << endl;
cout << "Sum: " << MathOperations::add(10, 20) << endl;

return 0;
}

Example: Bank Account with Static Interest Rate:

cpp
class BankAccount {
private:
int accountNumber;
double balance;
static double interestRate; // Same for all accounts
static int totalAccounts;

public:
BankAccount(int accNo, double bal) {
accountNumber = accNo;
balance = bal;
totalAccounts++;
}

void applyInterest() {
balance += balance * interestRate / 100;
}

void display() {
cout << "Account: " << accountNumber
<< ", Balance: " << balance << endl;
}

static void setInterestRate(double rate) {


interestRate = rate;
}

static double getInterestRate() {


return interestRate;
}

static int getTotalAccounts() {


return totalAccounts;
}
};

double BankAccount::interestRate = 5.0;


int BankAccount::totalAccounts = 0;

int main() {
BankAccount acc1(1001, 10000);
BankAccount acc2(1002, 20000);
BankAccount acc3(1003, 15000);
cout << "Interest Rate: " << BankAccount::getInterestRate() << "%" << endl;
cout << "Total Accounts: " << BankAccount::getTotalAccounts() << endl;

// Change interest rate for all accounts


BankAccount::setInterestRate(6.5);

[Link]();
[Link]();
[Link]();

[Link]();
[Link]();
[Link]();

return 0;
}

5.5 Friend Functions


Definition: Non-member functions that have access to private and protected members of a class.

Characteristics:

Declared with friend keyword inside class


Not a member function (no this pointer)
Can access private and protected members
Not affected by access specifiers (public/private/protected)
Can be friend of multiple classes
Friendship is not mutual or inherited

Syntax:

cpp

class ClassName {
private:
// Private members

friend returnType functionName(parameters);


};

A. Friend Function - Basic Example


cpp

class Box {
private:
int length;

public:
Box(int l) : length(l) {}

// Friend function declaration


friend void displayLength(Box b);
};

// Friend function definition


void displayLength(Box b) {
// Can access private member
cout << "Length: " << [Link] << endl;
}

int main() {
Box b1(10);
displayLength(b1); // Friend function can access private data

return 0;
}

B. Friend Function with Multiple Parameters

cpp
class Distance {
private:
int meters;

public:
Distance(int m) : meters(m) {}

// Friend function to add two Distance objects


friend Distance addDistance(Distance d1, Distance d2);

void display() {
cout << "Distance: " << meters << " meters" << endl;
}
};

Distance addDistance(Distance d1, Distance d2) {


Distance temp(0);
[Link] = [Link] + [Link]; // Access private members
return temp;
}

int main() {
Distance d1(100), d2(200);
Distance d3 = addDistance(d1, d2);
[Link](); // 300 meters

return 0;
}

C. Friend Function Common to Multiple Classes

cpp
class ClassB; // Forward declaration

class ClassA {
private:
int valueA;

public:
ClassA(int v) : valueA(v) {}

friend void showValues(ClassA a, ClassB b);


};

class ClassB {
private:
int valueB;

public:
ClassB(int v) : valueB(v) {}

friend void showValues(ClassA a, ClassB b);


};

// Friend to both classes


void showValues(ClassA a, ClassB b) {
cout << "ClassA value: " << [Link] << endl;
cout << "ClassB value: " << [Link] << endl;
}

int main() {
ClassA objA(10);
ClassB objB(20);
showValues(objA, objB);

return 0;
}

D. Friend Class

Definition: An entire class declared as friend can access private members of another class.

cpp
class Engine {
private:
int horsepower;

public:
Engine(int hp) : horsepower(hp) {}

friend class Car; // Car class is friend


};

class Car {
private:
string model;
Engine engine;

public:
Car(string m, int hp) : model(m), engine(hp) {}

void display() {
cout << "Model: " << model << endl;
// Can access Engine's private member
cout << "Horsepower: " << [Link] << endl;
}
};

int main() {
Car myCar("Tesla Model S", 670);
[Link]();

return 0;
}

E. Practical Example: Complex Number Operations

cpp
class Complex {
private:
float real;
float imag;

public:
Complex(float r = 0, float i = 0) : real(r), imag(i) {}

void display() {
cout << real << " + " << imag << "i" << endl;
}

// Friend functions for arithmetic operations


friend Complex add(Complex c1, Complex c2);
friend Complex subtract(Complex c1, Complex c2);
friend Complex multiply(Complex c1, Complex c2);
};

Complex add(Complex c1, Complex c2) {


Complex temp;
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
return temp;
}

Complex subtract(Complex c1, Complex c2) {


Complex temp;
[Link] = [Link] - [Link];
[Link] = [Link] - [Link];
return temp;
}

Complex multiply(Complex c1, Complex c2) {


Complex temp;
[Link] = [Link] * [Link] - [Link] * [Link];
[Link] = [Link] * [Link] + [Link] * [Link];
return temp;
}

int main() {
Complex c1(3, 4), c2(1, 2);

Complex sum = add(c1, c2);


Complex diff = subtract(c1, c2);
Complex prod = multiply(c1, c2);

cout << "Sum: ";


[Link]();

cout << "Difference: ";


[Link]();

cout << "Product: ";


[Link]();

return 0;
}

When to Use Friend Functions:

When function needs access to private data of multiple classes


For operator overloading (especially binary operators)
When non-member function needs intimate access to class internals
To improve readability in certain operations

Disadvantages of Friend Functions:

Breaks encapsulation
Violates data hiding principle
Can make code harder to maintain
Should be used sparingly

5.6 Dynamic Memory Allocation


Definition: Allocating memory at runtime using new and delete operators.

A. Dynamic Memory for Basic Data Types

Syntax:

cpp

// Allocation
dataType* pointer = new dataType;
dataType* pointer = new dataType(initialValue);

// Deallocation
delete pointer;

Examples:
cpp

// Integer
int* ptr = new int;
*ptr = 10;
cout << *ptr << endl;
delete ptr;

// Integer with initialization


int* p = new int(25);
cout << *p << endl;
delete p;

// Float
float* fptr = new float(3.14);
cout << *fptr << endl;
delete fptr;

// Character
char* ch = new char('A');
cout << *ch << endl;
delete ch;

B. Dynamic Arrays

Syntax:

cpp

// Allocation
dataType* pointer = new dataType[size];

// Deallocation
delete[] pointer; // Note: delete[] for arrays

Examples:

cpp
// Integer array
int n = 5;
int* arr = new int[n];

// Initialize array
for (int i = 0; i < n; i++) {
arr[i] = i * 10;
}

// Display array
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}

// Free memory
delete[] arr;

// 2D Array (array of pointers)


int rows = 3, cols = 4;
int** matrix = new int*[rows];
for (int i = 0; i < rows; i++) {
matrix[i] = new int[cols];
}

// Initialize
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = i * cols + j;
}
}

// Free memory
for (int i = 0; i < rows; i++) {
delete[] matrix[i];
}
delete[] matrix;

C. Dynamic Objects

cpp
class Student {
private:
int id;
string name;

public:
Student() {
id = 0;
name = "Unknown";
cout << "Default constructor" << endl;
}

Student(int i, string n) : id(i), name(n) {


cout << "Parameterized constructor" << endl;
}

~Student() {
cout << "Destructor for " << name << endl;
}

void display() {
cout << "ID: " << id << ", Name: " << name << endl;
}
};

int main() {
// Single object
Student* s1 = new Student();
s1->display();
delete s1; // Destructor called

// Object with parameters


Student* s2 = new Student(101, "Alice");
s2->display();
delete s2;

// Array of objects
int n = 3;
Student* students = new Student[n];

// Cannot pass parameters with array new


// Must use setter methods

delete[] students; // All destructors called


return 0;
}

D. Dynamic Memory Management Example

cpp
class DynamicString {
private:
char* str;
int length;

public:
// Constructor
DynamicString(const char* s) {
length = strlen(s);
str = new char[length + 1]; // +1 for null terminator
strcpy(str, s);
cout << "String created: " << str << endl;
}

// Copy constructor (deep copy)


DynamicString(const DynamicString& other) {
length = [Link];
str = new char[length + 1];
strcpy(str, [Link]);
cout << "Copy created: " << str << endl;
}

// Destructor
~DynamicString() {
cout << "Deleting: " << str << endl;
delete[] str;
}

void display() {
cout << "String: " << str << ", Length: " << length << endl;
}

void concatenate(const char* s) {


int newLength = length + strlen(s);
char* temp = new char[newLength + 1];

strcpy(temp, str);
strcat(temp, s);

delete[] str; // Free old memory


str = temp;
length = newLength;
}
};
int main() {
DynamicString s1("Hello");
[Link]();

[Link](" World");
[Link]();

DynamicString s2 = s1; // Copy constructor


[Link]();

return 0;
}

E. Memory Leak Prevention

cpp
class MemoryManager {
private:
int* data;
int size;

public:
MemoryManager(int s) {
size = s;
data = new int[size];
cout << "Memory allocated for " << size << " integers" << endl;
}

~MemoryManager() {
delete[] data;
cout << "Memory freed" << endl;
}

void setData(int index, int value) {


if (index >= 0 && index < size) {
data[index] = value;
}
}

int getData(int index) {


if (index >= 0 && index < size) {
return data[index];
}
return -1;
}
};

int main() {
// Good practice: Using scope
{
MemoryManager mm(10);
[Link](0, 100);
cout << [Link](0) << endl;
} // Destructor called automatically, memory freed

// Memory leak example (BAD)


// int* ptr = new int[100];
// Forgot to delete[] ptr; // MEMORY LEAK!

// Good practice
int* ptr = new int[100];
// Use ptr...
delete[] ptr; // Always free memory

return 0;
}

F. new vs malloc

Comparison:

Aspect new malloc


Type Operator Function
Returns Actual data type pointer void* (needs casting)
Size Calculation Automatic Manual (using sizeof)
Constructor Called automatically Not called
Failure Throws exception Returns NULL
Syntax int* p = new int; int* p = (int*)malloc(sizeof(int));

Examples:

cpp

// Using new (C++ way - RECOMMENDED)


int* p1 = new int;
int* arr1 = new int[10];
Student* s1 = new Student();

delete p1;
delete[] arr1;
delete s1;

// Using malloc (C way - NOT RECOMMENDED in C++)


int* p2 = (int*)malloc(sizeof(int));
int* arr2 = (int*)malloc(10 * sizeof(int));
Student* s2 = (Student*)malloc(sizeof(Student));
// Note: Constructor NOT called with malloc!

free(p2);
free(arr2);
free(s2);

Important Points:
1. Always pair new with delete and new[] with delete[]
2. Never mix new/delete with malloc/free
3. Always check for allocation failure
4. Avoid memory leaks by proper deallocation
5. Use smart pointers (C++11) for automatic memory management

G. Exception Handling with new

cpp

#include <iostream>
#include <new> // For bad_alloc
using namespace std;

int main() {
try {
// Attempt to allocate huge memory
int* hugeArray = new int[1000000000];
delete[] hugeArray;
}
catch (bad_alloc& e) {
cout << "Memory allocation failed: " << [Link]() << endl;
}

// Using nothrow
int* ptr = new(nothrow) int[1000000000];
if (ptr == nullptr) {
cout << "Memory allocation failed (no exception)" << endl;
} else {
delete[] ptr;
}

return 0;
}

6. SUMMARY & KEY POINTS


Basic Elements

Identifiers: Names for variables, functions, classes (must follow naming rules)
Keywords: Reserved words with special meaning (cannot be used as identifiers)
Constants: Fixed values (literals, const, constexpr, #define)
Variables: Named memory locations with data type
Statements: Complete instructions
Expressions: Combinations that evaluate to a value
Operators

Arithmetic: +, -, *, /, %
Relational: ==, !=, <, >, <=, >=
Logical: &&, ||, !
Assignment: =, +=, -=, *=, /=, %=
Increment/Decrement: ++, --
Bitwise: &, |, ^, ~, <<, >>
Special: sizeof, ?: (ternary), , (comma)

Type Conversion

Implicit: Automatic (smaller to larger type)


Explicit: Manual casting (C-style, function-style, C++ casts)
C++ Casts: static_cast, dynamic_cast, const_cast, reinterpret_cast

Control Structures

Conditional: if, if-else, if-else-if, switch, nested if


Loops: for, while, do-while, range-based for
Jump Statements: break (exit loop/switch), continue (skip iteration), goto (avoid!)

Classes and Objects

Class: Blueprint/template with data and functions


Object: Instance of a class
Access Specifiers: private, public, protected
Member Functions: Functions inside class (accessors, mutators, utility)
this Pointer: Points to current object

Advanced Features
Constructors: Special functions to initialize objects
Default, Parameterized, Copy, Overloaded constructors
Destructors: Special functions to cleanup (~ClassName)
Inline Functions: Code expanded at call site (small functions)
Static Members: Belong to class, not objects (shared by all)
Friend Functions: Non-member functions accessing private data
Nested Classes: Class inside another class

Memory Management

Dynamic Allocation: new operator (allocates at runtime)


Dynamic Deallocation: delete operator (frees memory)
Arrays: new[], delete[] for dynamic arrays
Objects: new creates object on heap, delete destroys
Memory Leak: Forgetting to delete allocated memory

Best Practices
1. Use meaningful identifier names
2. Initialize variables when declaring
3. Prefer const over #define
4. Use C++ style casts over C-style
5. Always pair new with delete
6. Use initialization lists in constructors
7. Make single-parameter constructors explicit
8. Declare member functions const when they don't modify data
9. Use inline for small, frequently called functions
10. Avoid friend functions unless necessary
11. Always free dynamically allocated memory
12. Check for null pointer before dereferencing

7. COMMON MISTAKES TO AVOID


1. Forgetting semicolon after class definition

cpp

class MyClass {
// ...
}; // Semicolon required!

2. Not initializing variables

cpp

int x; // Garbage value


cout << x; // Undefined behavior

3. Array index out of bounds

cpp

int arr[5];
arr[5] = 10; // ERROR! Valid indices: 0-4

4. Mismatching new and delete

cpp

int* p = new int[10];


delete p; // WRONG! Should be delete[]

5. Using object after delete


cpp

Student* s = new Student();


delete s;
s->display(); // Dangling pointer! Undefined behavior

6. Forgetting break in switch

cpp

switch(x) {
case 1:
cout << "One";
// Missing break - falls through!
case 2:
cout << "Two";
break;
}

7. Comparing floats with ==

cpp

float a = 0.1 + 0.2;


if (a == 0.3) // May fail due to precision
// Use: fabs(a - 0.3) < 0.0001

8. Not handling copy constructor properly

cpp
class Array {
int* data;
public:
Array(int size) { data = new int[size]; }
// Missing copy constructor leads to shallow copy!
~Array() { delete[] data; }
};

8. PRACTICE QUESTIONS
Conceptual Questions:

1. What is the difference between const and #define?


2. Explain the order of constructor and destructor calls in inheritance.
3. Why should we use delete[] for arrays instead of delete?
4. What is the purpose of the this pointer?
5. When would you use a friend function?

Programming Exercises:

1. Create a class BankAccount with dynamic memory for transaction history


2. Implement a Matrix class with constructor, destructor, and operations
3. Write a program using nested classes for University-Department-Student
4. Create a String class with dynamic memory and copy constructor
5. Implement a static counter across multiple object creations

This completes Unit 2: Introduction to C++. Study each section thoroughly and practice the examples!

You might also like