Introduction to C++

C++ is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C language. It supports both procedural and object-oriented programming paradigms.

Key Features of C++

  • Object-Oriented: Supports encapsulation, inheritance, and polymorphism
  • Platform Dependent: C++ programs are platform-dependent and need to be compiled for each platform
  • Mid-level Language: Can be used for both system programming and application development
  • Rich Library Support: Has a rich set of library functions
  • Memory Management: Supports dynamic memory allocation

Basic Structure of a C++ Program

// Simple C++ Program #include <iostream> using namespace std; int main() { cout << "Hello, World!"; return 0; }
Note: The using namespace std; directive allows us to use names for objects and variables from the standard library without the std:: prefix.

Tokens and Data Types

Tokens are the smallest individual units in a program. C++ has the following tokens:

Types of Tokens

  • Keywords: Predefined reserved words with special meaning (e.g., int, float, if, for)
  • Identifiers: Names given to variables, functions, etc.
  • Constants: Fixed values that don't change
  • Strings: Sequence of characters
  • Operators: Symbols that perform operations

Data Types in C++

  • Basic Data Types: int, char, float, double, bool, void
  • Derived Data Types: array, pointer, reference
  • User-defined Data Types: structure, union, enum, class
// Variable Declaration and Initialization int age = 25; float salary = 50000.50; char grade = 'A'; bool isEmployed = true;

Operators in C++

Operators are symbols that perform operations on operands.

Types of Operators

  • Arithmetic Operators: +, -, *, /, %
  • Relational Operators: ==, !=, >, <, >=, <=
  • Logical Operators: &&, ||, !
  • Assignment Operators: =, +=, -=, *=, /=
  • Increment/Decrement Operators: ++, --
  • Bitwise Operators: &, |, ^, ~, <<, >>
  • Ternary Operator: ? :
// Examples of Operators int a = 10, b = 5; int sum = a + b; // Arithmetic bool result = (a > b); // Relational bool logic = (a > 0 && b > 0); // Logical a += 5; // Assignment

Control Structures

Control structures determine the flow of execution in a program.

Decision Making Statements

  • if statement: Executes a block if condition is true
  • if-else statement: Executes one block if true, another if false
  • switch statement: Selects one of many code blocks to execute
// if-else example int marks = 85; if (marks >= 90) { cout << "Grade A"; } else if (marks >= 75) { cout << "Grade B"; } else { cout << "Grade C"; }

Looping Statements

  • for loop: Executes a block for a specific number of times
  • while loop: Executes a block while condition is true
  • do-while loop: Executes a block at least once, then repeats while condition is true
// for loop example for (int i = 0; i < 5; i++) { cout << i << " "; } // Output: 0 1 2 3 4

Functions in C++

A function is a block of code that performs a specific task.

Function Components

  • Function Declaration: Tells the compiler about a function's name, return type, and parameters
  • Function Definition: Provides the actual body of the function
  • Function Call: Invokes the function
// Function example #include <iostream> using namespace std; // Function declaration int add(int a, int b); int main() { int result = add(5, 3); // Function call cout << "Sum: " << result; return 0; } // Function definition int add(int a, int b) { return a + b; }

Types of Functions

  • Library Functions: Predefined in C++ libraries
  • User-defined Functions: Created by the programmer
Exam Tip: Remember the difference between call by value and call by reference. In call by value, changes made to parameters don't affect the actual arguments. In call by reference, changes affect the actual arguments.

Object-Oriented Programming (OOP) Concepts

OOP is a programming paradigm that uses objects and classes to organize code.

Four Pillars of OOP

  • Encapsulation: Wrapping data and functions into a single unit (class)
  • Abstraction: Hiding complex implementation details and showing only essential features
  • Inheritance: Creating new classes from existing ones
  • Polymorphism: Ability to take many forms

Class and Object

A class is a blueprint for objects, and an object is an instance of a class.

// Class and Object example class Student { private: string name; int age; public: // Member function to set data void setData(string n, int a) { name = n; age = a; } // Member function to display data void display() { cout << "Name: " << name << ", Age: " << age; } }; int main() { Student s1; // Creating object s1.setData("John", 20); s1.display(); return 0; }

Constructors and Destructors

Constructors

A constructor is a special member function that is automatically called when an object is created.

  • Default Constructor: Has no parameters
  • Parameterized Constructor: Has parameters
  • Copy Constructor: Initializes an object using another object of the same class
// Constructor example class Rectangle { private: int length, width; public: // Default constructor Rectangle() { length = 0; width = 0; } // Parameterized constructor Rectangle(int l, int w) { length = l; width = w; } // Copy constructor Rectangle(Rectangle &obj) { length = obj.length; width = obj.width; } int area() { return length * width; } };

Destructors

A destructor is a special member function that is automatically called when an object is destroyed.

// Destructor example class Example { public: Example() { cout << "Constructor called"; } ~Example() { cout << "Destructor called"; } };

Inheritance

Inheritance allows a class to inherit properties and characteristics from another class.

Types of Inheritance

  • Single Inheritance: A class inherits from one base class
  • Multiple Inheritance: A class inherits from multiple base classes
  • Multilevel Inheritance: A class inherits from a derived class
  • Hierarchical Inheritance: Multiple classes inherit from a single base class
  • Hybrid Inheritance: Combination of two or more types of inheritance
// Single Inheritance example class Animal { // Base class public: void eat() { cout << "Eating..."; } }; class Dog : public Animal { // Derived class public: void bark() { cout << "Barking..."; } }; int main() { Dog d; d.eat(); // Inherited from Animal d.bark(); // Defined in Dog return 0; }
Exam Tip: Understand the different access specifiers (public, private, protected) and how they affect inheritance.

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common super class.

Types of Polymorphism

  • Compile-time Polymorphism (Static): Achieved through function overloading and operator overloading
  • Runtime Polymorphism (Dynamic): Achieved through function overriding using virtual functions
// Function Overloading example class Math { public: int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } };
// Function Overriding example class Base { public: virtual void show() { cout << "Base class show"; } }; class Derived : public Base { public: void show() { cout << "Derived class show"; } }; int main() { Base *b; Derived d; b = &d; b->show(); // Output: Derived class show return 0; }

Templates

Templates allow generic programming by enabling functions and classes to operate with generic types.

Function Templates

// Function template example template <typename T> T maximum(T a, T b) { return (a > b) ? a : b; } int main() { cout << maximum(10, 5) << endl; // int cout << maximum(10.5, 5.5) << endl; // double return 0; }

Class Templates

// Class template example template <class T> class Calculator { private: T num1, num2; public: Calculator(T n1, T n2) { num1 = n1; num2 = n2; } T add() { return num1 + num2; } }; int main() { Calculator<int> intCalc(5, 3); Calculator<double> doubleCalc(5.5, 3.3); cout << intCalc.add() << endl; // 8 cout << doubleCalc.add() << endl; // 8.8 return 0; }

Exception Handling

Exception handling allows programs to handle runtime errors gracefully.

Exception Handling Keywords

  • try: Block of code to test for errors
  • catch: Block of code to handle the error
  • throw: Throws an exception when a problem is detected
// Exception handling example #include <iostream> using namespace std; int main() { int numerator, denominator; cout << "Enter numerator and denominator: "; cin >> numerator >> denominator; try { if (denominator == 0) { throw "Division by zero error!"; } cout << "Result: " << numerator/denominator; } catch (const char* msg) { cout << "Error: " << msg; } return 0; }

File Handling

C++ provides fstream library for file operations.

File Stream Classes

  • ofstream: Output file stream (for writing to files)
  • ifstream: Input file stream (for reading from files)
  • fstream: General file stream (for both reading and writing)
// File handling example #include <iostream> #include <fstream> using namespace std; int main() { // Writing to a file ofstream outFile("example.txt"); outFile << "Hello, File Handling in C++!"; outFile.close(); // Reading from a file ifstream inFile("example.txt"); string content; getline(inFile, content); cout << "File content: " << content; inFile.close(); return 0; }