Introduction to C++ Syntax
C++ is a powerful, general-purpose programming language that extends the C language with object-oriented features. Created by Bjarne Stroustrup in 1985, C++ combines low-level memory manipulation with high-level abstractions, making it ideal for system software, application software, game development, drivers, and performance-critical applications.
Basic Program Structure
Every C++ program includes these fundamental elements:
// This is a comment
/* This is a
multi-line comment */
#include <iostream> // Header inclusion
// Namespace declaration
using namespace std; // Optional but common
// Function declaration
void myFunction(); // Forward declaration
// Main function - program entry point
int main() {
// Code statements
cout << "Hello World!";
// Return statement
return 0; // Indicates successful execution
}
// Function definition
void myFunction() {
// Function body
}
Data Types
Primitive Types
Type | Description | Size | Example |
---|
bool | Boolean | 1 byte | bool isActive = true; |
char | Character | 1 byte | char grade = 'A'; |
int | Integer | 4 bytes | int count = 42; |
float | Floating-point | 4 bytes | float price = 10.99f; |
double | Double precision float | 8 bytes | double pi = 3.14159; |
void | No value | – | Used in functions, pointers |
wchar_t | Wide character | 2 or 4 bytes | wchar_t letter = L'Ω'; |
Type Modifiers
Modifier | Effect | Example |
---|
short | Reduces size | short int num = 10; |
long | Increases size | long int bigNum = 10000000L; |
signed | Can be negative (default) | signed int num = -42; |
unsigned | Non-negative only | unsigned int positiveNum = 42; |
long long | Extended size for integers | long long int veryBig = 9223372036854775807LL; |
Derived Types
Type | Description | Example |
---|
Arrays | Collection of elements | int numbers[5] = {1, 2, 3, 4, 5}; |
References | Alias to a variable | int& ref = original; |
Pointers | Stores memory address | int* ptr = &value; |
Variables & Constants
Variable Declaration Syntax
data_type variable_name; // Declaration
data_type variable_name = initial_value; // Initialization
data_type variable1, variable2, variable3; // Multiple variables
auto variable_name = value; // Type deduction (C++11)
Constants
const int MAX_VALUE = 100; // Compile-time constant
constexpr int COMPILED_VAL = MAX_VALUE * 2; // C++11 compile-time expression
// Enumeration constants
enum Color {RED, GREEN, BLUE};
enum class Fruit : int {APPLE = 0, ORANGE, BANANA}; // Scoped enum (C++11)
// Define directive (not recommended for most cases)
#define PI 3.14159
Operators
Arithmetic Operators
Operator | Description | Example |
---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus | a % b |
++ | Increment | a++ or ++a |
-- | Decrement | a-- or --a |
Relational Operators
Operator | Description | Example |
---|
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal | a >= b |
<= | Less than or equal | a <= b |
<=> | Three-way comparison (C++20) | a <=> b |
Logical Operators
Operator | Description | Example |
---|
&& | Logical AND | a && b |
|| | Logical OR | a || b |
! | Logical NOT | !a |
Bitwise Operators
Operator | Description | Example |
---|
& | Bitwise AND | a & b |
| | Bitwise OR | a | b |
^ | Bitwise XOR | a ^ b |
~ | Bitwise NOT | ~a |
<< | Left shift | a << b |
>> | Right shift | a >> b |
Assignment Operators
Operator | Description | Example |
---|
= | Assign | a = b |
+= | Add and assign | a += b |
-= | Subtract and assign | a -= b |
*= | Multiply and assign | a *= b |
/= | Divide and assign | a /= b |
%= | Modulus and assign | a %= b |
&= | Bitwise AND and assign | a &= b |
|= | Bitwise OR and assign | a |= b |
^= | Bitwise XOR and assign | a ^= b |
<<= | Left shift and assign | a <<= b |
>>= | Right shift and assign | a >>= b |
Other Operators
Operator | Description | Example |
---|
sizeof | Size of variable/type | sizeof(int) |
. | Member access | object.member |
-> | Member access via pointer | pointer->member |
:: | Scope resolution | Class::member |
?: | Ternary conditional | condition ? expr1 : expr2 |
, | Comma | expr1, expr2 |
.* | Pointer to member | object.*memberPtr |
->* | Pointer to member via pointer | pointer->*memberPtr |
new | Dynamic memory allocation | int* p = new int; |
delete | Dynamic memory deallocation | delete p; |
new[] | Dynamic array allocation | int* arr = new int[10]; |
delete[] | Dynamic array deallocation | delete[] arr; |
() | Function call | function() |
[] | Array subscript | array[index] |
Control Flow
Conditional Statements
// If statement
if (condition) {
// Code executed if condition is true
}
// If-else statement
if (condition) {
// Code executed if condition is true
} else {
// Code executed if condition is false
}
// If-else if-else statement
if (condition1) {
// Code executed if condition1 is true
} else if (condition2) {
// Code executed if condition2 is true
} else {
// Code executed if all conditions are false
}
// Switch statement
switch (expression) {
case value1:
// Code executed if expression equals value1
break;
case value2:
// Code executed if expression equals value2
break;
default:
// Code executed if no match is found
break;
}
// Ternary operator
variable = (condition) ? valueIfTrue : valueIfFalse;
Loops
// For loop
for (initialization; condition; update) {
// Code executed for each iteration
}
// Range-based for loop (C++11)
for (type variable : collection) {
// Code executed for each element
}
// While loop
while (condition) {
// Code executed while condition is true
}
// Do-while loop
do {
// Code executed at least once and then while condition is true
} while (condition);
// Loop control
break; // Exit loop
continue; // Skip to next iteration
goto label; // Jump to labeled statement (discouraged)
Functions
Function Declaration & Definition
// Basic function
return_type function_name(parameter_type1 param1, parameter_type2 param2) {
// Function body
return value; // Return statement (if not void)
}
// Function with default parameters
void function_name(int param1 = default_value) {
// Function body
}
// Function declaration (prototype)
return_type function_name(parameter_type1, parameter_type2);
// Inline function suggestion
inline int add(int a, int b) {
return a + b;
}
// Function overloading
void print(int value);
void print(double value);
void print(string value);
Lambda Expressions (C++11)
// Basic lambda
auto lambda = []() { cout << "Hello Lambda"; };
// Lambda with parameters
auto add = [](int a, int b) { return a + b; };
// Lambda with capture list
int x = 10;
auto addX = [x](int a) { return a + x; }; // Capture by value
auto addXRef = [&x](int a) { return a + x; }; // Capture by reference
auto addAll = [=](int a) { return a + x; }; // Capture all by value
auto addAllRef = [&](int a) { return a + x; }; // Capture all by reference
// Lambda with return type
auto divide = [](int a, int b) -> double { return a / (double)b; };
Classes & Objects
Class Definition
class ClassName {
private:
// Private members (accessible only within the class)
int privateVariable;
protected:
// Protected members (accessible in this class and derived classes)
int protectedVariable;
public:
// Public members (accessible from anywhere)
int publicVariable;
// Constructor
ClassName(int value) : privateVariable(value) {
// Constructor body
}
// Destructor
~ClassName() {
// Destructor body
}
// Member function
void memberFunction() {
// Function body
}
// Const member function (doesn't modify object state)
int getValue() const {
return privateVariable;
}
// Static member function
static void staticFunction() {
// Operates on class, not on objects
}
};
Creating & Using Objects
// Object creation on stack
ClassName obj1(10);
// Object creation on heap
ClassName* obj2 = new ClassName(20);
delete obj2; // Don't forget to delete heap objects
// Accessing members
obj1.publicVariable = 30;
obj1.memberFunction();
// Accessing via pointer
obj2->publicVariable = 40;
obj2->memberFunction();
Inheritance
// Base class
class Base {
public:
void baseFunction() { }
};
// Derived class with public inheritance
class Derived : public Base {
public:
void derivedFunction() { }
};
// Multiple inheritance
class MultiDerived : public Base1, public Base2 {
// ...
};
// Virtual inheritance (for diamond problem)
class D : virtual public B {
// ...
};
Polymorphism
class Base {
public:
// Virtual function (can be overridden)
virtual void virtualFunction() {
// Base implementation
}
// Pure virtual function (must be overridden in derived classes)
virtual void pureVirtualFunction() = 0;
};
class Derived : public Base {
public:
// Override
void virtualFunction() override {
// Derived implementation
}
void pureVirtualFunction() override {
// Implementation required
}
};
// Using polymorphism
Base* basePtr = new Derived();
basePtr->virtualFunction(); // Calls Derived implementation
delete basePtr;
Templates
Function Templates
// Function template
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
// Using the template
int maxInt = max<int>(3, 7); // Explicit type
double maxDouble = max(3.5, 2.5); // Type deduction
Class Templates
// Class template
template <typename T, int Size = 10>
class Array {
private:
T elements[Size];
public:
T& operator[](int index) {
return elements[index];
}
int size() const {
return Size;
}
};
// Using the template
Array<int, 5> intArray;
Array<string> stringArray; // Uses default Size=10
Template Specialization
// Primary template
template <typename T>
class MyClass {
public:
void function() {
// Generic implementation
}
};
// Explicit specialization
template <>
class MyClass<int> {
public:
void function() {
// Specialized implementation for int
}
};
Namespaces
// Namespace definition
namespace MyNamespace {
int value = 5;
void function() { }
// Nested namespace
namespace Nested {
int nestedValue = 10;
}
}
// Using namespace elements
int x = MyNamespace::value;
MyNamespace::function();
int y = MyNamespace::Nested::nestedValue;
// Namespace alias
namespace MN = MyNamespace;
int z = MN::value;
// Using directive (brings all names into current scope)
using namespace MyNamespace;
int a = value; // Directly accessible
// Using declaration (brings specific name into current scope)
using MyNamespace::function;
function(); // Directly accessible
Exception Handling
// Try-catch block
try {
// Code that might throw exceptions
throw SomeException("Error message");
} catch (const SomeException& e) {
// Handle specific exception
cout << e.what();
} catch (const std::exception& e) {
// Handle standard exceptions
cout << e.what();
} catch (...) {
// Handle all other exceptions
cout << "Unknown exception";
}
// Function with exception specification (deprecated in C++17, removed in C++20)
void function() throw(ExceptionType1, ExceptionType2) {
// Can throw only ExceptionType1 or ExceptionType2
}
// Noexcept specification (C++11)
void safeFunction() noexcept {
// Promises not to throw exceptions
}
void conditionalNoexcept() noexcept(condition) {
// Noexcept depends on condition
}
Standard Library Components
Input/Output Streams
#include <iostream>
using namespace std;
// Output to console
cout << "Hello" << 42 << endl;
// Input from console
int value;
cin >> value;
// File operations
#include <fstream>
ofstream outFile("output.txt"); // Output file stream
outFile << "Writing to file" << endl;
outFile.close();
ifstream inFile("input.txt"); // Input file stream
string line;
getline(inFile, line);
inFile.close();
// String streams
#include <sstream>
stringstream ss;
ss << "Value: " << 42;
string result = ss.str();
Containers
#include <vector>
#include <list>
#include <map>
#include <set>
#include <array>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <stack>
// Vector (dynamic array)
vector<int> vec = {1, 2, 3};
vec.push_back(4);
int third = vec[2];
// List (doubly-linked list)
list<int> lst = {1, 2, 3};
lst.push_back(4);
lst.push_front(0);
// Map (associative array)
map<string, int> scores;
scores["Alice"] = 95;
int aliceScore = scores["Alice"];
// Set (collection of unique values)
set<int> uniqueNums = {3, 1, 4, 1, 5}; // Stores 1, 3, 4, 5
// Array (fixed-size array, C++11)
array<int, 3> arr = {1, 2, 3};
int second = arr[1];
// Unordered map (hash table, C++11)
unordered_map<string, int> hashMap;
hashMap["key"] = 100;
// Unordered set (hash set, C++11)
unordered_set<int> hashSet = {3, 1, 4, 1, 5}; // Stores 1, 3, 4, 5
// Queue (FIFO)
queue<int> q;
q.push(1);
int front = q.front();
q.pop();
// Stack (LIFO)
stack<int> s;
s.push(1);
int top = s.top();
s.pop();
Algorithms
#include <algorithm>
#include <vector>
using namespace std;
vector<int> v = {3, 1, 4, 1, 5, 9};
// Sorting
sort(v.begin(), v.end()); // Sort in ascending order
sort(v.begin(), v.end(), greater<int>()); // Sort in descending order
// Searching
auto it = find(v.begin(), v.end(), 4); // Find element
bool exists = binary_search(v.begin(), v.end(), 4); // Binary search (requires sorted range)
// Counting
int count_val = count(v.begin(), v.end(), 1); // Count occurrences
int count_even = count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }); // Count with predicate
// Min/Max
auto min_it = min_element(v.begin(), v.end());
auto max_it = max_element(v.begin(), v.end());
auto [min_it, max_it] = minmax_element(v.begin(), v.end()); // C++17
// Transformations
transform(v.begin(), v.end(), v.begin(), [](int x) { return x * 2; }); // Double each element
// For_each
for_each(v.begin(), v.end(), [](int x) { cout << x << " "; }); // Process each element
Smart Pointers (C++11)
#include <memory>
using namespace std;
// Unique pointer (exclusive ownership)
unique_ptr<int> uptr = make_unique<int>(42); // C++14
int value = *uptr; // Dereference
uptr.reset(); // Release ownership and delete
// Shared pointer (shared ownership)
shared_ptr<int> sptr1 = make_shared<int>(42);
shared_ptr<int> sptr2 = sptr1; // Both share ownership
int count = sptr1.use_count(); // Reference count
// Weak pointer (non-owning reference to shared object)
weak_ptr<int> wptr = sptr1;
if (auto temp = wptr.lock()) { // Get shared_ptr if object exists
// Use temp
}
Modern C++ Features (C++11 and beyond)
C++11 Features
// Auto type deduction
auto i = 42;
auto d = 42.0;
// Range-based for loops
for (auto& item : container) {
// Process item
}
// Nullptr
int* ptr = nullptr;
// Enum classes
enum class Color { Red, Green, Blue };
Color c = Color::Red;
// Strongly-typed enums
enum class Status : uint8_t { Good, Bad, Unknown };
// Initializer lists
vector<int> v = {1, 2, 3, 4};
int array[] = {1, 2, 3, 4};
// Uniform initialization
class C {
public:
int x;
double y;
};
C c{1, 2.0};
// Delegating constructors
class D {
public:
D(int x) : D(x, 0) {}
D(int x, int y) : x_(x), y_(y) {}
private:
int x_, y_;
};
// Move semantics
void move_example(string&& str) {
string new_str = std::move(str); // Transfer ownership
}
// Lambda expressions (covered earlier)
// Variadic templates
template<typename... Args>
void print(Args... args) {
(cout << ... << args) << endl; // C++17 fold expression
}
C++14 Features
// Generic lambdas
auto generic = [](auto x, auto y) { return x + y; };
// Return type deduction
auto add(int x, int y) { return x + y; } // Return type is deduced
// Variable templates
template<typename T>
constexpr T pi = T(3.1415926535897932385);
double circumference = 2 * pi<double> * radius;
// Binary literals
int binary = 0b10101010; // Binary representation
C++17 Features
// Structured bindings
pair<int, string> p = {1, "one"};
auto [num, name] = p;
map<string, int> m = {{"one", 1}, {"two", 2}};
for (const auto& [key, value] : m) {
cout << key << ": " << value << endl;
}
// if constexpr
template<typename T>
void process(T t) {
if constexpr (is_integral_v<T>) {
// Only compiled for integral types
} else {
// For other types
}
}
// Inline variables
inline int global_var = 42;
// std::optional
#include <optional>
optional<int> maybe_value();
if (auto val = maybe_value(); val.has_value()) {
cout << *val;
}
// std::variant
#include <variant>
variant<int, string> var = "hello";
if (holds_alternative<string>(var)) {
cout << get<string>(var);
}
// std::any
#include <any>
any a = 42;
if (a.type() == typeid(int)) {
cout << any_cast<int>(a);
}
C++20 Features
// Concepts
template<typename T>
concept Addable = requires(T a, T b) {
{ a + b } -> std::convertible_to<T>;
};
template<Addable T>
T add(T a, T b) {
return a + b;
}
// Ranges
#include <ranges>
vector<int> v = {1, 2, 3, 4, 5};
auto even = v | views::filter([](int n) { return n % 2 == 0; });
// Three-way comparison (spaceship operator)
struct Point {
int x;
int y;
auto operator<=>(const Point&) const = default;
};
// Modules (support varies by compiler)
// import <iostream>;
// import mymodule;
// Coroutines
#include <coroutine>
#include <optional>
// Feature test macros
#ifdef __cpp_concepts
// Code using concepts
#endif
Common Pitfalls and Best Practices
Memory Management
- Always delete what you new, delete[] what you new[]
- Prefer smart pointers (unique_ptr, shared_ptr) over raw pointers
- Be cautious of memory leaks, especially in exception paths
- Use containers from the standard library instead of manual memory management when possible
- Implement the Rule of Three/Five/Zero for classes that manage resources
Performance Considerations
- Pass large objects by const reference to avoid copying
- Use move semantics for transferring ownership
- Consider pass-by-value for small, copyable types
- Avoid unnecessary memory allocations
- Preallocate container capacity when size is known
- Use reserve() on vectors before adding many elements
Code Style
- Be consistent with naming conventions
- Use meaningful variable and function names
- Keep functions small and focused
- Follow the Single Responsibility Principle
- Use const whenever possible
- Prefer auto for complex types or when type is obvious
- Use nullptr instead of NULL or 0 for pointers
Compatibility
- Be aware of compiler differences
- Use feature test macros for new language features
- Be careful with implementation-defined behavior
- Specify the C++ standard version in your build system
- Be mindful of platform-specific code
Resources for Further Learning
Official Documentation
Books
- “The C++ Programming Language” by Bjarne Stroustrup
- “Effective C++” by Scott Meyers
- “C++ Primer” by Stanley Lippman
- “Modern C++ Design” by Andrei Alexandrescu
- “A Tour of C++” by Bjarne Stroustrup
Online Resources