- Published on
C++ Programming Guide - From Basics to Advanced Concepts
- Authors
- Name
- Muhammad Huzaifa
C++ Programming Guide - From Basics to Advanced Concepts
Welcome to this comprehensive C++ programming guide! Whether you're a beginner or looking to refresh your knowledge, this post covers everything from basic syntax to advanced concepts with practical examples.
Table of Contents
- Getting Started
- Basic Syntax
- Data Types and Variables
- Control Structures
- Functions
- Object-Oriented Programming
- Memory Management
- STL and Containers
- Advanced Concepts
- Best Practices
Getting Started
C++ is a powerful, general-purpose programming language that supports both procedural and object-oriented programming paradigms. It's widely used in system programming, game development, and high-performance applications.
Setting Up Your Environment
// Hello World Program
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Basic Syntax
Comments and Basic Structure
// Single line comment
/* Multi-line comment */
#include <iostream> // Include header files
using namespace std; // Use standard namespace
int main() {
// Your code here
return 0;
}
Data Types and Variables
Primitive Data Types
#include <iostream>
#include <string>
int main() {
// Integer types
int age = 25;
short smallNumber = 100;
long bigNumber = 1000000L;
long long veryBigNumber = 1000000000LL;
// Floating point types
float price = 19.99f;
double preciseValue = 3.14159265359;
long double veryPrecise = 3.141592653589793238L;
// Character types
char grade = 'A';
wchar_t wideChar = L'Ω';
// Boolean
bool isStudent = true;
// String
string name = "Muhammad Huzaifa";
// Output
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Grade: " << grade << endl;
cout << "Is Student: " << (isStudent ? "Yes" : "No") << endl;
return 0;
}
Constants and Literals
#include <iostream>
int main() {
// Constants
const int MAX_SIZE = 100;
const double PI = 3.14159;
// Literals
int decimal = 42;
int octal = 052; // Octal
int hexadecimal = 0x2A; // Hexadecimal
int binary = 0b101010; // Binary (C++14)
cout << "Decimal: " << decimal << endl;
cout << "Octal: " << octal << endl;
cout << "Hexadecimal: " << hexadecimal << endl;
cout << "Binary: " << binary << endl;
return 0;
}
Control Structures
If-Else Statements
#include <iostream>
int main() {
int score = 85;
if (score >= 90) {
cout << "Grade: A" << endl;
} else if (score >= 80) {
cout << "Grade: B" << endl;
} else if (score >= 70) {
cout << "Grade: C" << endl;
} else if (score >= 60) {
cout << "Grade: D" << endl;
} else {
cout << "Grade: F" << endl;
}
return 0;
}
Loops
#include <iostream>
#include <vector>
int main() {
// For loop
cout << "For loop:" << endl;
for (int i = 1; i <= 5; i++) {
cout << "Iteration " << i << endl;
}
// While loop
cout << "\nWhile loop:" << endl;
int count = 1;
while (count <= 3) {
cout << "Count: " << count << endl;
count++;
}
// Do-while loop
cout << "\nDo-while loop:" << endl;
int num = 1;
do {
cout << "Number: " << num << endl;
num++;
} while (num <= 3);
// Range-based for loop (C++11)
cout << "\nRange-based for loop:" << endl;
vector<int> numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
cout << "Value: " << num << endl;
}
return 0;
}
Switch Statement
#include <iostream>
int main() {
char operation = '+';
int a = 10, b = 5;
int result;
switch (operation) {
case '+':
result = a + b;
cout << "Addition: " << result << endl;
break;
case '-':
result = a - b;
cout << "Subtraction: " << result << endl;
break;
case '*':
result = a * b;
cout << "Multiplication: " << result << endl;
break;
case '/':
if (b != 0) {
result = a / b;
cout << "Division: " << result << endl;
} else {
cout << "Division by zero!" << endl;
}
break;
default:
cout << "Invalid operation!" << endl;
}
return 0;
}
Functions
Basic Functions
#include <iostream>
#include <cmath>
// Function declaration
int add(int a, int b);
double calculateCircleArea(double radius);
void printMessage(string message);
int main() {
int sum = add(5, 3);
cout << "Sum: " << sum << endl;
double area = calculateCircleArea(5.0);
cout << "Circle area: " << area << endl;
printMessage("Hello from function!");
return 0;
}
// Function definitions
int add(int a, int b) {
return a + b;
}
double calculateCircleArea(double radius) {
return 3.14159 * radius * radius;
}
void printMessage(string message) {
cout << "Message: " << message << endl;
}
Function Overloading
#include <iostream>
// Function overloading
int multiply(int a, int b) {
return a * b;
}
double multiply(double a, double b) {
return a * b;
}
int multiply(int a, int b, int c) {
return a * b * c;
}
int main() {
cout << "Int multiplication: " << multiply(5, 3) << endl;
cout << "Double multiplication: " << multiply(5.5, 3.2) << endl;
cout << "Three numbers: " << multiply(2, 3, 4) << endl;
return 0;
}
Object-Oriented Programming
Classes and Objects
#include <iostream>
#include <string>
class Student {
private:
string name;
int age;
double gpa;
public:
// Constructor
Student(string n, int a, double g) : name(n), age(a), gpa(g) {}
// Getter methods
string getName() const { return name; }
int getAge() const { return age; }
double getGPA() const { return gpa; }
// Setter methods
void setName(string n) { name = n; }
void setAge(int a) { age = a; }
void setGPA(double g) { gpa = g; }
// Method
void displayInfo() const {
cout << "Name: " << name << ", Age: " << age << ", GPA: " << gpa << endl;
}
};
int main() {
// Creating objects
Student student1("Muhammad Huzaifa", 20, 3.8);
Student student2("Ali Ahmed", 22, 3.5);
// Using methods
student1.displayInfo();
student2.displayInfo();
// Modifying data
student1.setGPA(3.9);
cout << "Updated GPA: " << student1.getGPA() << endl;
return 0;
}
Inheritance
#include <iostream>
#include <string>
// Base class
class Person {
protected:
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {}
virtual void display() const {
cout << "Name: " << name << ", Age: " << age << endl;
}
virtual ~Person() {} // Virtual destructor
};
// Derived class
class Employee : public Person {
private:
string department;
double salary;
public:
Employee(string n, int a, string dept, double sal)
: Person(n, a), department(dept), salary(sal) {}
void display() const override {
cout << "Employee - Name: " << name << ", Age: " << age
<< ", Department: " << department << ", Salary: $" << salary << endl;
}
};
int main() {
Person person("John Doe", 30);
Employee employee("Jane Smith", 25, "IT", 50000);
person.display();
employee.display();
return 0;
}
Memory Management
Dynamic Memory Allocation
#include <iostream>
int main() {
// Dynamic allocation
int* ptr = new int(42);
cout << "Value: " << *ptr << endl;
// Array allocation
int size = 5;
int* arr = new int[size];
// Initialize array
for (int i = 0; i < size; i++) {
arr[i] = i * 2;
}
// Print array
cout << "Array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
// Clean up memory
delete ptr;
delete[] arr;
return 0;
}
Smart Pointers (C++11)
#include <iostream>
#include <memory>
int main() {
// Unique pointer
std::unique_ptr<int> ptr1 = std::make_unique<int>(42);
cout << "Unique ptr value: " << *ptr1 << endl;
// Shared pointer
std::shared_ptr<int> ptr2 = std::make_shared<int>(100);
std::shared_ptr<int> ptr3 = ptr2; // Shared ownership
cout << "Shared ptr value: " << *ptr2 << endl;
cout << "Reference count: " << ptr2.use_count() << endl;
// Weak pointer
std::weak_ptr<int> weakPtr = ptr2;
if (auto locked = weakPtr.lock()) {
cout << "Weak ptr value: " << *locked << endl;
}
return 0;
}
STL and Containers
Vector
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Creating vector
vector<int> numbers = {5, 2, 8, 1, 9};
// Adding elements
numbers.push_back(7);
numbers.insert(numbers.begin() + 2, 3);
// Accessing elements
cout << "First element: " << numbers[0] << endl;
cout << "Last element: " << numbers.back() << endl;
// Iterating
cout << "Vector contents: ";
for (int num : numbers) {
cout << num << " ";
}
cout << endl;
// Sorting
sort(numbers.begin(), numbers.end());
cout << "Sorted: ";
for (int num : numbers) {
cout << num << " ";
}
cout << endl;
return 0;
}
Map and Set
#include <iostream>
#include <map>
#include <set>
#include <string>
int main() {
// Map example
map<string, int> ages;
ages["Muhammad"] = 20;
ages["Ali"] = 22;
ages["Ahmed"] = 19;
cout << "Ages:" << endl;
for (const auto& pair : ages) {
cout << pair.first << ": " << pair.second << endl;
}
// Set example
set<int> uniqueNumbers = {5, 2, 8, 2, 5, 1};
cout << "\nUnique numbers: ";
for (int num : uniqueNumbers) {
cout << num << " ";
}
cout << endl;
return 0;
}
Advanced Concepts
Templates
#include <iostream>
// Function template
template<typename T>
T getMax(T a, T b) {
return (a > b) ? a : b;
}
// Class template
template<typename T>
class Stack {
private:
vector<T> elements;
public:
void push(T element) {
elements.push_back(element);
}
T pop() {
if (elements.empty()) {
throw runtime_error("Stack is empty!");
}
T element = elements.back();
elements.pop_back();
return element;
}
bool empty() const {
return elements.empty();
}
size_t size() const {
return elements.size();
}
};
int main() {
// Using function template
cout << "Max of 5 and 3: " << getMax(5, 3) << endl;
cout << "Max of 5.5 and 3.2: " << getMax(5.5, 3.2) << endl;
// Using class template
Stack<int> intStack;
intStack.push(10);
intStack.push(20);
intStack.push(30);
cout << "Stack size: " << intStack.size() << endl;
cout << "Popped: " << intStack.pop() << endl;
cout << "Popped: " << intStack.pop() << endl;
return 0;
}
Lambda Expressions (C++11)
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Lambda to find even numbers
auto isEven = [](int n) { return n % 2 == 0; };
// Count even numbers
int evenCount = count_if(numbers.begin(), numbers.end(), isEven);
cout << "Even numbers count: " << evenCount << endl;
// Lambda with capture
int multiplier = 3;
auto multiply = [multiplier](int n) { return n * multiplier; };
cout << "Multiplied by 3: ";
for (int num : numbers) {
cout << multiply(num) << " ";
}
cout << endl;
return 0;
}
Best Practices
1. Use const whenever possible
const int MAX_SIZE = 100;
const string COMPANY_NAME = "Tech Corp";
void printInfo(const string& name, const int& age) {
cout << "Name: " << name << ", Age: " << age << endl;
}
2. Prefer references over pointers
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
3. Use RAII (Resource Acquisition Is Initialization)
class FileHandler {
private:
FILE* file;
public:
FileHandler(const char* filename) {
file = fopen(filename, "r");
}
~FileHandler() {
if (file) {
fclose(file);
}
}
};
4. Use auto for type deduction
auto numbers = vector<int>{1, 2, 3, 4, 5};
auto it = numbers.begin();
Conclusion
C++ is a powerful language that offers both high-level abstractions and low-level control. This guide covered the fundamental concepts, but there's always more to learn. Practice regularly, work on projects, and don't hesitate to explore advanced topics like multithreading, networking, and graphics programming.
Next Steps
- Practice coding - Solve problems on platforms like LeetCode, HackerRank
- Build projects - Create games, applications, or system tools
- Learn advanced topics - Multithreading, networking, graphics
- Read good code - Study open-source C++ projects
- Join communities - Engage with C++ developer communities
Happy coding! 🚀
Have questions about C++ programming? Feel free to reach out and let's discuss!