C++ Programming Tutorial
1. Hello World:
Let's begin with a simple "Hello, World!" program to understand the basic structure of a C++ program.
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
- `#include <iostream>`: Includes the input/output stream library.
- `int main()`: The entry point of a C++ program. Execution begins here.
- `std::cout`: Represents the standard output stream.
- `<<`: The insertion operator used to output data.
- `std::endl`: Manipulator to insert a newline and flush the stream.
2. Variables and Data Types:
Learn how to declare variables and work with various data types in C++.
int age = 25;
double pi = 3.14159;
char grade = 'A';
bool isStudent = true;
- `int`, `double`, `char`, `bool`: Basic data types in C++.
- Variable names must start with a letter and can include letters, digits, and underscores.
3. User Input:
Allow users to provide input using the `cin` stream.
#include <iostream>
int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num;
std::cout << "You entered: " << num << std::endl;
return 0;
}
- `std::cin`: Standard input stream used for user input.
4. Arithmetic Operators:
Perform basic arithmetic operations.
int a = 10, b = 5;
int sum = a + b;
int difference = a - b;
int product = a * b;
double quotient = static_cast<double>(a) / b;
int remainder = a % b;
- `+`, `-`, `*`, `/`, `%`: Basic arithmetic operators.
5. Conditional Statements (if, else if, else):
Make decisions in your program using conditional statements.
int num = 10;
if (num > 0) {
std::cout << "Number is positive." << std::endl;
} else if (num < 0) {
std::cout << "Number is negative." << std::endl;
} else {
std::cout << "Number is zero." << std::endl;
}
- `if`, `else if`, `else`: Keywords for conditional branching.
6. Loops (for, while, do-while):
Repeat a block of code using loops.
// Using a for loop
for (int i = 1; i <= 5; ++i) {
std::cout << i << " ";
}
// Using a while loop
int count = 0;
while (count < 3) {
std::cout << "Count: " << count << std::endl;
++count;
}
// Using a do-while loop
int n = 5;
do {
std::cout << n << " ";
--n;
} while (n > 0);
- `for`, `while`, `do-while`: Different types of loops in C++.
7. Arrays:
Store multiple values in a single variable using arrays.
int numbers[5] = {1, 2, 3, 4, 5};
// Accessing array elements
int thirdNumber = numbers[2];
- Arrays are zero-indexed.
8. Functions:
Organize your code into functions for better modularity.
// Function declaration
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(3, 5);
std::cout << "Sum: " << result << std::endl;
return 0;
}
- `return`: Statement to return a value from a function.
- Function declaration consists of return type, name, and parameters.
9. Scope and Lifetime:
Understand the scope and lifetime of variables.
int globalVar = 10; // Global variable
int main() {
int localVar = 5; // Local variable
{
int blockVar = 7; // Variable within a block
}
// localVar and blockVar are not accessible here
return 0;
}
- Global variables are accessible throughout the program.
- Local variables are limited to the scope they are defined in.
10. Pointers:
Learn how to work with memory addresses using pointers.
int num = 42;
int *ptr = # // Pointer to an int
// Dereferencing a pointer
std::cout << "Value at ptr: " << *ptr << std::endl;
- `&`: Address-of operator.
- `*`: Dereference operator.
11. References:
Create an alias for a variable using references.
int num = 7;
int &refNum = num; // Reference to num
refNum = 10; // Updates num to 10
- References provide a convenient way to work with variables indirectly.
12. Object-Oriented Programming (OOP):
Introduce the basics of OOP using classes and objects.
class Circle {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() {
return 3.14159 * radius * radius;
}
};
int main() {
Circle myCircle(5.0);
std::cout << "Area: " << myCircle.area() << std::endl;
return 0;
}
- `class`: Keyword to define a class.
- `private`: Access specifier to restrict direct access to class members.
13. Constructors and Destructors:
Understand constructors and destructors in classes.
class Person {
private:
std::string name;
public:
Person(const std::string &n) : name(n) {
std::cout << "Constructor called." << std::endl;
}
~Person() {
std::cout << "Destructor called." << std::endl;
}
};
int main() {
Person person("Alice");
// Destructor called when 'person' goes out of scope
return 0;
}
- Constructors initialize class objects.
- Destructors perform cleanup when objects are destroyed.
14. Inheritance:
Learn about inheritance and base/derived classes.
class Animal {
public:
void speak() {
std::cout << "Animal speaks." << std::endl;
}
};
class Dog : public Animal {
public:
void speak() {
std::cout << "Dog barks." << std::endl;
}
};
int main() {
Dog myDog;
myDog.speak(); // Calls Dog's speak() method
return 0;
}
- `public`: Access specifier for inheritance.
- Base class: The class from which another class inherits.
15. Polymorphism:
Understand runtime polymorphism using virtual functions.
class Shape {
public:
virtual void draw() {
std::cout << "Drawing a shape." << std::endl;
}
};
class Circle : public Shape {
public:
void draw() override {
std::cout << "Drawing a circle." << std::endl;
}
};
int main() {
Shape *shapePtr = new Circle();
shapePtr->draw(); // Calls Circle's draw() due to dynamic binding
delete shapePtr;
return 0;
}
- `virtual`: Keyword to enable dynamic binding.
- `override`: Indicates that a function is intended to override a virtual function in the base class.
16. Encapsulation:
Explore encapsulation by controlling access to class members.
class BankAccount {
private:
double balance;
public:
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount account;
account.deposit(1000);
std::cout << "Balance: " << account.getBalance() << std::endl;
return 0;
}
- `private`: Data members with restricted access.
17. Templates:
Learn about function and class templates for generic programming.
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
int main() {
int result = max(3, 7);
std::cout << "Max: " << result << std::endl;
return 0;
}
- `template`: Keyword to define templates.
- Function templates allow generic functions.
18. Standard Template Library (STL):
Introduce STL containers and algorithms.
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {5, 2, 8, 3, 1};
std::sort(numbers.begin(), numbers.end());
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
- `<vector>`: Include statement for the vector container.
- `<algorithm>`: Include statement for various algorithms.
19. Exception Handling:
Handle runtime errors using exception handling.
try {
int result = 10 / 0;
} catch (const std::exception &e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
- `try`: Encloses code that might raise exceptions.
- `catch`: Catches and handles exceptions.
20. File I/O:
Read from and write to files using file streams.
#include <fstream>
int main() {
std::ofstream outputFile("output.txt");
if (outputFile.is_open()) {
outputFile << "Hello, File I/O!";
outputFile.close();
}
return 0;
}
- `std::ofstream`: Output file stream.
- `is_open()`: Checks if a file is open.
21. Namespaces:
Organize code using namespaces to avoid naming conflicts.
namespace Math {
int add(int a, int b) {
return a + b;
}
}
int main() {
int result = Math::add(5, 3);
return 0;
}
- `namespace`: Keyword to define a namespace.
22. Preprocessor Directives:
Use preprocessor directives for conditional compilation.
- `#define`: Defines a macro.
23. Type Casting:
Convert between different data types.
double pi = 3.14159;
int approxPi = static_cast<int>(pi);
- `static_cast`: Explicit type casting.
24. Enumerations:
Create user-defined enumerations.
enum Color { RED, GREEN, BLUE };
Color myColor = GREEN;
- `enum`: Keyword to define an enumeration.
25. Lambda Expressions:
Define anonymous functions using lambda expressions.
auto add = [](int a, int b) { return a + b; };
int result = add(4, 5);
- Lambdas provide a concise way to define functions.
26. Smart Pointers:
Use smart pointers for automatic memory management.
#include <memory>
std::shared_ptr<int> numPtr = std::make_shared<int>(42);
- `std::shared_ptr`: Shared ownership smart pointer.
27. Standard Input/Output Manipulators:
Manipulate input and output formatting.
#include <iomanip>
double value = 123.456789;
std::cout << std::fixed << std::setprecision(2) << value;
- `std::fixed`, `std::setprecision`: Manipulators for output formatting.
28. Operator Overloading:
Define custom behavior for operators.
class Complex {
public:
double real, imag;
Complex operator+(const Complex &other) {
Complex result;
result.real = real + other.real;
result.imag = imag + other.imag;
return result;
}
};
int main() {
Complex a = {2.0, 3.0};
Complex b = {1.0, 2.0};
Complex c = a + b; // Calls operator+()
return 0;
}
- `operator+`: Operator overloading for addition.
29. const and constexpr:
Understand the usage of `const` and `constexpr`.
const int maxLimit = 100;
constexpr double pi = 3.14159;
- `const`: Indicates that a value cannot be modified.
- `constexpr`: Indicates a value that can be computed at compile time.
30. Multi-threading:
Explore basic multi-threading using the `<thread>` library.
#include <iostream>
#include <thread>
void printNumbers() {
for (int i = 1; i <= 5; ++i) {
std::cout << i << " ";
}
std::cout << std::endl;
}
int main() {
std::thread t(printNumbers);
t.join(); // Wait for the thread to finish
return 0;
}
- `<thread>`: Header for multi-threading support.
- `std::thread`: Class for managing threads.