C++ Basics
Learn C++ programming fundamentals
C++ Basics
C++ is a general-purpose programming language with object-oriented, generic, and functional features. This guide covers the fundamentals you need to get started with C++ programming.
Variables
C++ is statically typed - you must declare variable types:
// Variable declaration
int age = 30;
double price = 19.99;
float temperature = 98.6f;
char grade = 'A';
bool isActive = true;
// Type modifiers
unsigned int positive = 100;
long long bigNumber = 9223372036854775807LL;
const int MAX_SIZE = 100; // Constant
constexpr int SIZE = 50; // Compile-time constant
// Auto type deduction (C++11)
auto name = "C++"; // const char*
auto number = 42; // int
auto decimal = 3.14; // double
// Multiple variables
int x = 1, y = 2, z = 3;
Data Types
C++ has fundamental and compound types:
// Fundamental types
int integer = 42;
double decimal = 3.14;
char character = 'C';
bool flag = true;
void* pointer = nullptr; // C++11
// Strings
#include
std::string text = "Hello, World!";
std::string name = "C++";
// String operations
text.length(); // Get length
text + " " + name; // Concatenation
text.substr(0, 5); // "Hello"
text.find("World"); // Find position
Arrays
C++ has built-in arrays and std::array:
// Built-in arrays
int numbers[5] = {1, 2, 3, 4, 5};
int arr[] = {1, 2, 3}; // Size inferred
// Accessing elements
numbers[0] = 10; // First element
int first = numbers[0];
// Multi-dimensional arrays
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int value = matrix[0][1]; // 2
// std::array (C++11, recommended)
#include
std::array numbers = {1, 2, 3, 4, 5};
numbers.size(); // Get size
numbers.at(0); // Safe access (bounds checking)
Vectors
Vectors are dynamic arrays:
#include
// Creating vectors
std::vector numbers = {1, 2, 3, 4, 5};
std::vector fruits;
std::vector empty(10); // 10 zeros
// Adding elements
fruits.push_back("apple");
fruits.push_back("banana");
fruits.insert(fruits.begin(), "kiwi"); // Insert at beginning
// Accessing elements
fruits[0]; // "kiwi" (no bounds checking)
fruits.at(0); // "kiwi" (with bounds checking)
fruits.front(); // First element
fruits.back(); // Last element
// Removing elements
fruits.pop_back(); // Remove last
fruits.erase(fruits.begin()); // Remove first
fruits.clear(); // Remove all
// Vector methods
fruits.size(); // Get size
fruits.empty(); // Check if empty
fruits.capacity(); // Get capacity
Loops
C++ offers several iteration methods:
// For loop
for (int i = 0; i < 5; i++) {
std::cout << i << std::endl;
}
// Range-based for loop (C++11)
std::vector numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
std::cout << num << std::endl;
}
// Range-based for with auto
for (auto num : numbers) {
std::cout << num << std::endl;
}
// Range-based for with references
for (auto& num : numbers) {
num *= 2; // Modify in place
}
// While loop
int count = 0;
while (count < 5) {
std::cout << count << std::endl;
count++;
}
// Do-while loop
do {
std::cout << count << std::endl;
count--;
} while (count > 0);
// Loop control
for (int i = 0; i < 10; i++) {
if (i == 3) {
continue; // Skip to next iteration
}
if (i == 7) {
break; // Exit loop
}
std::cout << i << std::endl;
}
Conditionals
Control flow with if/else statements:
// If/else
int age = 20;
if (age >= 18) {
std::cout << "Adult" << std::endl;
} else if (age >= 13) {
std::cout << "Teenager" << std::endl;
} else {
std::cout << "Child" << std::endl;
}
// Ternary operator
std::string status = (age >= 18) ? "Adult" : "Minor";
// Logical operators
if (age >= 18 && hasLicense) {
std::cout << "Can drive" << std::endl;
}
if (isWeekend || isHoliday) {
std::cout << "Day off" << std::endl;
}
if (!isComplete) {
std::cout << "Not done yet" << std::endl;
}
// Switch statement
char grade = 'B';
switch (grade) {
case 'A':
std::cout << "Excellent" << std::endl;
break;
case 'B':
std::cout << "Good" << std::endl;
break;
case 'C':
std::cout << "Average" << std::endl;
break;
default:
std::cout << "Needs improvement" << std::endl;
}
Functions
Functions are defined with return type and parameters:
// Function definition
int add(int x, int y) {
return x + y;
}
// Function with default parameters
void greet(std::string name = "World") {
std::cout << "Hello, " << name << "!" << std::endl;
}
// Function overloading
int multiply(int a, int b) {
return a * b;
}
double multiply(double a, double b) {
return a * b;
}
// Pass by reference
void increment(int& value) {
value++;
}
int num = 5;
increment(num); // num is now 6
// Pass by pointer
void setValue(int* ptr, int value) {
*ptr = value;
}
int x = 0;
setValue(&x, 42); // x is now 42
// Lambda functions (C++11)
auto add = [](int x, int y) { return x + y; };
int result = add(5, 3); // 8
// Lambda with capture
int multiplier = 2;
auto multiply = [multiplier](int x) { return x * multiplier; };
int result = multiply(5); // 10
Classes
C++ supports object-oriented programming:
// Class definition
class Person {
private:
std::string name;
int age;
public:
// Constructor
Person(std::string name, int age) : name(name), age(age) {}
// Getter methods
std::string getName() const {
return name;
}
int getAge() const {
return age;
}
// Setter methods
void setName(const std::string& newName) {
name = newName;
}
void setAge(int newAge) {
age = newAge;
}
// Instance method
void introduce() const {
std::cout << "Hi, I'm " << name
<< " and I'm " << age << " years old" << std::endl;
}
};
// Creating objects
Person person("John", 30);
person.introduce();
person.setAge(31);
// Stack allocation (automatic)
Person p1("Alice", 25);
// Heap allocation (manual)
Person* p2 = new Person("Bob", 35);
delete p2; // Don't forget to delete!
// Smart pointers (C++11, recommended)
#include
std::unique_ptr p3 = std::make_unique("Charlie", 40);
// Automatically deleted when out of scope
STL Containers
Standard Template Library provides data structures:
#include
#include
#include
Pointers and References
C++ uses pointers and references:
// Pointers
int value = 42;
int* ptr = &value; // Pointer to value
*ptr = 100; // Dereference and modify
int val = *ptr; // Get value through pointer
// References
int& ref = value; // Reference to value
ref = 200; // Modify through reference
int val2 = ref; // Get value through reference
// Null pointer (C++11)
int* nullPtr = nullptr; // Safe null pointer
// Pointer arithmetic
int arr[5] = {1, 2, 3, 4, 5};
int* p = arr;
p++; // Points to arr[1]