C++ Basics: Identifiers, Keywords, Constants
C++ Basics: Identifiers, Keywords, Constants
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
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
cpp
// Constants: UPPER_CASE
const int MAX_SIZE = 100;
// Classes: PascalCase
class StudentRecord;
// Functions: camelCase
void calculateTotal();
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)
Floating-Point Literals:
cpp
Character Literals:
cpp
String Literals:
cpp
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
cpp
cpp
#define PI 3.14159
#define MAX 100
#define NEWLINE '\n'
cpp
cpp
Syntax:
cpp
data_type variable_name;
data_type variable_name = initial_value;
Basic Declarations:
cpp
// Single variable
int age;
double salary;
char grade;
// 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
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>
Statements
Types of Statements:
1. Expression Statement:
cpp
x = 10; // Assignment
y = x + 5; // Calculation
cout << "Hello"; // Function call
count++; // Increment
cpp
{
int x = 10;
int y = 20;
int sum = x + y;
} // Variables x, y, sum destroyed here
3. Declaration Statement:
cpp
4. Null Statement:
cpp
Expressions
Types of Expressions:
Arithmetic Expressions:
cpp
x+y
a*b+c
(a + b) / (c - d)
Relational Expressions:
cpp
Logical Expressions:
cpp
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)
cpp
result = (condition) ? value_if_true : value_if_false;
// Example
int max = (a > b) ? a : b;
string status = (age >= 18) ? "Adult" : "Minor";
Basic Syntax:
cpp
#include <iostream>
using namespace std;
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"
// Alignment
cout << left << setw(10) << "Name";
cout << right << setw(10) << "Value";
// Fill character
cout << setfill('*') << setw(10) << 42; // "********42"
Basic Syntax:
cpp
#include <iostream>
using namespace std;
Examples:
cpp
int age;
cout << "Enter age: ";
cin >> age;
// Multiple inputs
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;
// Character input
char grade;
cout << "Enter grade: ";
cin >> grade;
cpp
// Clear input buffer
[Link]();
A. Arithmetic Operators
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)
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
cpp
&& // Logical AND
|| // Logical OR
! // Logical NOT
// Examples
bool a = true, b = false;
// Practical examples
int age = 25;
bool hasLicense = true;
D. Assignment Operators
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)
cpp
++ // Increment
-- // Decrement
// 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
cpp
// Examples
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
Syntax:
cpp
Examples:
cpp
int a = 10, b = 20;
int max = (a > b) ? a : b; // max = 20
// Nested ternary
int grade = (score >= 90) ? 1 :
(score >= 80) ? 2 :
(score >= 70) ? 3 : 4;
H. sizeof Operator
cpp
int arr[10];
cout << sizeof(arr); // 40 (10 * 4)
I. Comma Operator
cpp
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
Important Points:
cpp
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'
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);
cpp
cpp
cpp
int x = 65;
char* ch = reinterpret_cast<char*>(&x);
// 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
B. if-else Statement
Syntax:
cpp
if (condition) {
// statements if true
} else {
// statements if false
}
Example:
cpp
C. if-else-if Ladder
Syntax:
cpp
if (condition1) {
// statements
} else if (condition2) {
// statements
} else if (condition3) {
// statements
} else {
// default statements
}
Example:
cpp
D. Nested if Statement
Example:
cpp
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;
}
A. for Loop
Syntax:
cpp
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
}
B. while Loop
Syntax:
cpp
while (condition) {
// statements
}
Examples:
cpp
// Sum of numbers
int sum = 0, n = 1;
while (n <= 10) {
sum += n;
n++;
}
cout << "Sum = " << sum;
// 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);
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;
}
// 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;
}
A. break Statement
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;
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
}
Syntax:
cpp
goto label;
// ...
label:
// statements
Example:
cpp
int i = 0;
start:
cout << i << " ";
i++;
if (i < 5)
goto start; // Jump back to start
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
};
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;
}
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:
cpp
class Example {
public:
int publicVar; // Accessible everywhere
void publicFunction() {
// Can be called from anywhere
}
};
3. protected:
cpp
class Base {
protected:
int protectedVar; // Accessible in derived classes
};
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.
cpp
class Circle {
private:
double radius;
public:
// Function defined inside class
void setRadius(double r) {
radius = r;
}
double getArea() {
return 3.14159 * radius * radius;
}
};
cpp
class Circle {
private:
double radius;
public:
void setRadius(double r); // Declaration
double getArea(); // Declaration
};
double Circle::getArea() {
return 3.14159 * radius * radius;
}
cpp
class Student {
private:
int age;
public:
int getAge() const { // const means doesn't modify data
return age;
}
};
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;
}
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
}
4.3 Objects
Definition: An instance of a class. It is a real-world entity that occupies memory.
cpp
ClassName objectName;
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;
[Link] = "Honda";
[Link] = "Civic";
[Link] = 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;
}
Syntax:
cpp
ClassName arrayName[size];
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
return 0;
}
cpp
class Point {
public:
int x, y;
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)
};
return 0;
}
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;
// Find topper
int topperIndex = 0;
for (int i = 1; i < n; i++) {
if (students[i].getAverage() > students[topperIndex].getAverage()) {
topperIndex = i;
}
}
return 0;
}
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
return 0;
}
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();
return 0;
}
cpp
class Point {
public:
int x, y;
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;
}
int main() {
Example obj;
[Link](10);
cout << [Link]() << endl; // 10
return 0;
}
Syntax:
cpp
class Outer {
private:
int outerData;
public:
void display() {
cout << "Inner class";
}
};
public:
void outerFunction() {
Inner innerObj;
[Link]();
}
};
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]();
return 0;
}
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;
}
Definition: Special member function automatically called when an object is created. Used to initialize object data.
Characteristics:
A. Default Constructor
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
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;
}
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
Syntax:
cpp
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;
}
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;
}
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
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
}
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
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;
}
int main() {
DynamicArray da(5);
[Link](0, 10);
[Link](1, 20);
cout << [Link](0) << endl;
// Destructor automatically called, memory freed
return 0;
}
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
Characteristics:
class Circle {
private:
double radius;
public:
// Automatically inline
void setRadius(double r) {
radius = r;
}
double getArea() {
return 3.14159 * radius * radius;
}
};
cpp
class Rectangle {
private:
int length, width;
public:
void setDimensions(int l, int w);
inline int area(); // Explicitly inline
};
cpp
class Math {
public:
// Inline - good for small functions
inline int square(int x) {
return x * x;
}
Large functions
Functions with loops, switch statements
Recursive functions
Virtual functions
Definition: Members that belong to the class rather than any specific object.
Characteristics:
Syntax:
cpp
class ClassName {
private:
static dataType variableName;
public:
static void functionName();
};
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;
}
int main() {
cout << "Initial count: " << Counter::getCount() << endl;
[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
Characteristics:
Example:
cpp
class MathOperations {
private:
static const double PI;
public:
// Static member function
static double circleArea(double radius) {
return PI * radius * radius;
}
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;
}
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;
}
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;
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
return 0;
}
Characteristics:
Syntax:
cpp
class ClassName {
private:
// Private members
class Box {
private:
int length;
public:
Box(int l) : length(l) {}
int main() {
Box b1(10);
displayLength(b1); // Friend function can access private data
return 0;
}
cpp
class Distance {
private:
int meters;
public:
Distance(int m) : meters(m) {}
void display() {
cout << "Distance: " << meters << " meters" << endl;
}
};
int main() {
Distance d1(100), d2(200);
Distance d3 = addDistance(d1, d2);
[Link](); // 300 meters
return 0;
}
cpp
class ClassB; // Forward declaration
class ClassA {
private:
int valueA;
public:
ClassA(int v) : valueA(v) {}
class ClassB {
private:
int valueB;
public:
ClassB(int v) : valueB(v) {}
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) {}
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;
}
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;
}
int main() {
Complex c1(3, 4), c2(1, 2);
return 0;
}
Breaks encapsulation
Violates data hiding principle
Can make code harder to maintain
Should be used sparingly
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;
// 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;
// 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() {
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
// Array of objects
int n = 3;
Student* students = new Student[n];
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;
}
// Destructor
~DynamicString() {
cout << "Deleting: " << str << endl;
delete[] str;
}
void display() {
cout << "String: " << str << ", Length: " << length << endl;
}
strcpy(temp, str);
strcat(temp, s);
[Link](" World");
[Link]();
return 0;
}
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;
}
int main() {
// Good practice: Using scope
{
MemoryManager mm(10);
[Link](0, 100);
cout << [Link](0) << endl;
} // Destructor called automatically, memory freed
// Good practice
int* ptr = new int[100];
// Use ptr...
delete[] ptr; // Always free memory
return 0;
}
F. new vs malloc
Comparison:
Examples:
cpp
delete p1;
delete[] arr1;
delete s1;
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
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;
}
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
Control Structures
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
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
cpp
class MyClass {
// ...
}; // Semicolon required!
cpp
cpp
int arr[5];
arr[5] = 10; // ERROR! Valid indices: 0-4
cpp
cpp
switch(x) {
case 1:
cout << "One";
// Missing break - falls through!
case 2:
cout << "Two";
break;
}
cpp
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:
Programming Exercises:
This completes Unit 2: Introduction to C++. Study each section thoroughly and practice the examples!