Basics of C++
1. Introduction to C++
C++ is a general-purpose programming language created as an extension of the C programming language. It supports both procedural and object-oriented programming paradigms.
Key Features:
- Object-Oriented: Supports classes and objects.
- Low-level Manipulation: Provides access to low-level system resources.
- Rich Standard Library: Includes a vast library of functions and classes.
- Performance: Offers high performance and efficiency.
2. Setting Up Your Environment
Before you start coding in C++, you need a compiler and an IDE (Integrated Development Environment). Common tools include:
- Compilers: GCC, Clang, MSVC
- IDEs: Visual Studio, Code::Blocks, Eclipse, CLion, or simply a text editor like VS Code with a terminal.
3. Hello, World!
Let's start with the classic "Hello, World!" program.
cpp#include <iostream> // Include the input-output stream library
int main() { // Main function where execution begins
std::cout << "Hello, World!" << std::endl; // Output "Hello, World!" to the console
return 0; // Return 0 to indicate successful completion
}
Explanation:
#include <iostream>
: Includes the standard input-output stream library.int main()
: The main function where the program execution starts.std::cout
: Standard character output stream.<<
: Stream insertion operator.std::endl
: Ends the line and flushes the output buffer.
4. Basic Syntax
Variables and Data Types
C++ supports several fundamental data types:
- int: Integer numbers (e.g.,
int age = 30;
) - double: Floating-point numbers (e.g.,
double pi = 3.14;
) - char: Single characters (e.g.,
char initial = 'A';
) - bool: Boolean values (
true
orfalse
) - string: Strings of characters (requires
#include <string>
, e.g.,std::string name = "John";
)
Example:
cpp#include <iostream>
#include <string>
int main() {
int age = 25;
double height = 5.9;
char initial = 'J';
bool isStudent = true;
std::string name = "John Doe";
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "Height: " << height << std::endl;
std::cout << "Initial: " << initial << std::endl;
std::cout << "Is Student: " << isStudent << std::endl;
return 0;
}
5. Operators
C++ supports a variety of operators, including:
- Arithmetic Operators:
+
,-
,*
,/
,%
- Relational Operators:
==
,!=
,<
,>
,<=
,>=
- Logical Operators:
&&
,||
,!
- Assignment Operators:
=
,+=
,-=
,*=
,/=
- Increment/Decrement Operators:
++
,--
Example:
cpp#include <iostream>
int main() {
int a = 10;
int b = 5;
std::cout << "a + b = " << a + b << std::endl;
std::cout << "a - b = " << a - b << std::endl;
std::cout << "a * b = " << a * b << std::endl;
std::cout << "a / b = " << a / b << std::endl;
std::cout << "a % b = " << a % b << std::endl;
bool result = (a > b) && (b > 0);
std::cout << "Result of (a > b) && (b > 0): " << result << std::endl;
return 0;
}
6. Control Structures
Conditional Statements
- if, else if, else
cpp#include <iostream>
int main() {
int number = 10;
if (number > 0) {
std::cout << "Positive number" << std::endl;
} else if (number < 0) {
std::cout << "Negative number" << std::endl;
} else {
std::cout << "Zero" << std::endl;
}
return 0;
}
Switch Statement
cpp#include <iostream>
int main() {
int choice = 2;
switch (choice) {
case 1:
std::cout << "Option 1 selected" << std::endl;
break;
case 2:
std::cout << "Option 2 selected" << std::endl;
break;
default:
std::cout << "Invalid option" << std::endl;
}
return 0;
}
Loops
- for Loop
cpp#include <iostream>
int main() {
for (int i = 0; i < 5; ++i) {
std::cout << "Iteration: " << i << std::endl;
}
return 0;
}
- while Loop
cpp#include <iostream>
int main() {
int count = 0;
while (count < 5) {
std::cout << "Count: " << count << std::endl;
++count;
}
return 0;
}
- do-while Loop
cpp#include <iostream>
int main() {
int count = 0;
do {
std::cout << "Count: " << count << std::endl;
++count;
} while (count < 5);
return 0;
}
7. Functions
Functions allow you to divide your program into reusable components.
Function Declaration and Definition
cpp#include <iostream>
// Function declaration
int add(int a, int b);
int main() {
int result = add(5, 3);
std::cout << "Sum: " << result << std::endl;
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
8. Arrays and Strings
Arrays
cpp#include <iostream>
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; ++i) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
return 0;
}
Strings
cpp#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello, World!";
std::cout << greeting << std::endl;
return 0;
}
9. Pointers
Pointers are variables that store memory addresses.
cpp#include <iostream>
int main() {
int num = 42;
int* ptr = #
std::cout << "Value of num: " << num << std::endl;
std::cout << "Address of num: " << ptr << std::endl;
std::cout << "Value at address stored in ptr: " << *ptr << std::endl;
return 0;
}
Intermediate Concepts
10. References
References are alternative names for existing variables.
cpp#include <iostream>
int main() {
int num = 10;
int& ref = num;
std::cout << "Value of num: " << num << std::endl;
std::cout << "Value of ref: " << ref << std::endl;
ref = 20;
std::cout << "Updated value of num: " << num << std::endl;
return 0;
}
11. Dynamic Memory Allocation
Dynamic memory allocation allows you to allocate memory during runtime using new
and delete
.
cpp#include <iostream>
int main() {
int* ptr = new int; // Allocate memory
*ptr = 42;
std::cout << "Value: " << *ptr << std::endl;
delete ptr; // Deallocate memory
return 0;
}
12. Structures
Structures allow you to group different data types together.
cpp#include <iostream>
struct Person {
std::string name;
int age;
};
int main() {
Person person;
person.name = "Alice";
person.age = 30;
std::cout << "Name: " << person.name << std::endl;
std::cout << "Age: " << person.age << std::endl;
return 0;
}
13. Enumerations
Enumerations are user-defined types that consist of named integral constants.
cpp#include <iostream>
enum Color { RED, GREEN, BLUE };
int main() {
Color color = GREEN;
if (color == GREEN) {
std::cout << "Color is Green" << std::endl;
}
return 0;
}
14. Namespaces
Namespaces prevent naming conflicts in large projects by grouping entities like classes, objects, and functions under a name.
cpp#include <iostream>
namespace MyNamespace {
void display() {
std::cout << "Inside MyNamespace" << std::endl;
}
}
int main() {
MyNamespace::display();
return 0;
}
15. Classes and Objects
Classes are blueprints for creating objects. They encapsulate data and functions.
cpp#include <iostream>
class Rectangle {
private:
double length;
double width;
public:
void setDimensions(double len, double wid) {
length = len;
width = wid;
}
double calculateArea() {
return length * width;
}
};
int main() {
Rectangle rect;
rect.setDimensions(5.0, 3.0);
std::cout << "Area of rectangle: " << rect.calculateArea() << std::endl;
return 0;
}
16. Inheritance
Inheritance allows one class to inherit attributes and methods from another class.
cpp#include <iostream>
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle : public Shape {
public:
int getArea() {
return (width * height);
}
};
int main() {
Rectangle rect;
rect.setWidth(5);
rect.setHeight(3);
std::cout << "Area of rectangle: " << rect.getArea() << std::endl;
return 0;
}
17. Polymorphism
Polymorphism allows methods to do different things based on the object it is acting upon.
cpp#include <iostream>
class Animal {
public:
virtual void sound() {
std::cout << "Animal sound" << std::endl;
}
};
class Dog : public Animal {
public:
void sound() override {
std::cout << "Woof" << std::endl;
}
};
int main() {
Animal* animal;
Dog dog;
animal = &dog;
animal->sound(); // Outputs "Woof" due to polymorphism
return 0;
}
18. Templates
Templates allow writing generic programs that work with any data type.
Function Template
cpp#include <iostream>
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
std::cout << "Sum of integers: " << add(3, 5) << std::endl;
std::cout << "Sum of doubles: " << add(2.5, 3.5) << std::endl;
return 0;
}
Class Template
cpp#include <iostream>
template <typename T>
class Calculator {
public:
T add(T a, T b) {
return a + b;
}
};
int main() {
Calculator<int> intCalc;
std::cout << "Sum of integers: " << intCalc.add(3, 5) << std::endl;
Calculator<double> doubleCalc;
std::cout << "Sum of doubles: " << doubleCalc.add(2.5, 3.5) << std::endl;
return 0;
}
19. Exception Handling
Exception handling is used to handle runtime errors using try
, catch
, and throw
.
cpp#include <iostream>
int main() {
try {
int denominator = 0;
if (denominator == 0) {
throw std::runtime_error("Division by zero error");
}
} catch (const std::exception& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
Advanced Concepts
20. Smart Pointers
Smart pointers manage memory automatically, reducing memory leaks.
Unique Pointer
cpp#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> ptr = std::make_unique<int>(42);
std::cout << "Value: " << *ptr << std::endl;
return 0;
}
Shared Pointer
cpp#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> ptr1 = std::make_shared<int>(42);
std::shared_ptr<int> ptr2 = ptr1; // Shared ownership
std::cout << "Value: " << *ptr1 << std::endl;
std::cout << "Value: " << *ptr2 << std::endl;
return 0;
}
21. Standard Template Library (STL)
The STL provides a collection of powerful, reusable classes and algorithms.
Vectors
cpp#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Maps
cpp#include <iostream>
#include <map>
int main() {
std::map<std::string, int> ageMap;
ageMap["Alice"] = 25;
ageMap["Bob"] = 30;
for (const auto& pair : ageMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
22. Multithreading
Multithreading allows concurrent execution of multiple threads.
cpp#include <iostream>
#include <thread>
void printNumbers(int count) {
for (int i = 0; i < count; ++i) {
std::cout << i << " ";
}
std::cout << std::endl;
}
int main() {
std::thread thread1(printNumbers, 5);
std::thread thread2(printNumbers, 5);
thread1.join(); // Wait for thread1 to finish
thread2.join(); // Wait for thread2 to finish
return 0;
}
23. Lambda Expressions
Lambda expressions are used to create anonymous functions.
cpp#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::for_each(numbers.begin(), numbers.end(), [](int num) {
std::cout << num * num << " ";
});
std::cout << std::endl;
return 0;
}
24. File I/O
File input and output operations are used to read and write files.
cpp#include <iostream>
#include <fstream>
#include <string>
int main() {
// Writing to a file
std::ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, File!" << std::endl;
outFile.close();
}
// Reading from a file
std::ifstream inFile("example.txt");
std::string line;
if (inFile.is_open()) {
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
inFile.close();
}
return 0;
}
Summary
In this comprehensive guide, we've covered the following C++ concepts:
- Basics: Variables, Data Types, Operators, Control Structures, Functions, Arrays, and Strings
- Intermediate: Pointers, References, Dynamic Memory Allocation, Structures, Enumerations, Namespaces, Classes and Objects, Inheritance, Polymorphism, Templates, Exception Handling
- Advanced: Smart Pointers, Standard Template Library (STL), Multithreading, Lambda Expressions, File I/O