
C++ Cheat Sheet: Quick Reference Guide for Programmers
Need a quick refresher on C++ syntax and concepts? This C++ cheat sheet provides a concise and easily accessible guide to the essentials, perfect for both beginners and experienced programmers. Keep this page bookmarked for quick reference.
C++ is a powerful, high-level programming language used for various applications. Developed in 1983 by Bjarne Stroustrup at Bell Labs, C++ remains a staple for software development. Let's dive into the core elements.
Your First C++ Program: A Simple Start
Here's a basic "Hello World!" program to get you started:
Output:
Hello World!
Don't worry if you don't understand everything right away! We'll break down the syntax.
Understanding the Basic C++ Syntax
Every C++ program follows a basic structure:
These components are the building blocks of any C++ application. The #include
directive, for example, brings in the input/output stream library. using namespace std;
avoids having to type std::
before elements like cout
.
Mastering Comments in C++: Documenting Your Code
Comments are essential for explaining your code and making it more readable. They are ignored by the compiler. Here are two types:
- Single-line comments: Use
//
for comments on a single line.// This is a single-line comment
- Multi-line comments: Use
/*
to start and*/
to end comments that span multiple lines./* This is a multi-line comment.It can span multiple lines. */
Variables in C++: Storing Data
Variables are named storage locations that hold values.
- They store data of a specific type (e.g., integer, character, etc.).
- You must declare variables before using them.
Identifiers and Constants: Naming Conventions
- Identifiers: Unique names for variables, functions, etc., must start with a letter or underscore.
- Constants: Fixed values that cannot be changed during program execution.
Data Types in C++: Defining Variable Types
Data types specify the kind of data a variable can hold.
- Integer (
int
): Stores whole numbers. Takes 4 bytes.int var = 123;
- Character (
char
): Stores single characters. Takes 1 byte.char var = 'a';
- Floating Point (
float
): Stores single-precision decimal numbers. Takes 4 bytes.float num = 1.23;
- Double (
double
): Stores double-precision decimal numbers. Takes 8 bytes.double num = 1.2345;
- Boolean (
bool
): Storestrue
orfalse
values.bool b = false;
- String (
string
): Stores sequences of characters (text). Include ``.string str = "GeeksforGeeks";
Input and Output in C++: Interacting with the User
C++ uses cin
for input and cout
for output, both found in the `` library.
- Input: Use
cin >> variable;
to read input from the user.int var; cin >> var;
- Output: Use
cout << "text" << variable;
to display output.cout << "Hello World!";
New Lines
Insert new lines in your output using \n
or endl
.
cout << "Hello World!\n";
cout << "Hello World!" << endl;
Conditional Statements in C++: Controlling Program Flow
Conditional statements execute different code blocks based on conditions.
-
if
statement: Executes code if a condition is true. -
Nested
if
statement: Anif
statement inside anotherif
statement. -
if-else
statement: Executes one block of code if the condition is true and another if it's false. -
else if
statement: Checks multiple conditions sequentially. -
Ternary Operator: A shorthand for
if-else
statements. -
switch
statement: Executes different code blocks based on the value of an expression.
Break and Default
break
: Exits theswitch
statement.default
: Executes if none of thecase
values match the expression.
Loops in C++: Repeating Code Blocks
Loops repeatedly execute a block of code.
-
for
Loop: Executes a block of code a fixed number of times. -
while
Loop: Executes a block of code as long as a condition is true. -
do-while
Loop: Executes a block of code at least once, then repeats as long as a condition is true.
Arrays in C++: Storing Collections of Data
Arrays store a fixed-size sequence of elements of the same data type.
Example
Multi-Dimensional Arrays
Arrays can have multiple dimensions. The most common is a 2-dimensional array.
Example:
Vectors in C++: Dynamic Arrays
Vectors are dynamic arrays that can grow or shrink in size. You need to include the `` header file.
Commonly Used Vector Functions
push_back()
: Adds an element to the end.pop_back()
: Removes the last element.clear()
: Removes all elements.empty()
: Checks if the vector is empty.at(i)
: Accesses the element at indexi
.front()
: Accesses the first element.back()
: Accesses the last element.erase()
: Removes an element at a specified position.
Example
Pointers and References in C++: Working with Memory
References
A reference is an alias for an existing variable.
ref
is now another name for var
.
Pointers
A pointer is a variable that stores the memory address of another variable. It uses the *
operator to declare a pointer and the &
operator to get the address of a variable.
Functions in C++: Reusable Code Blocks
Functions are reusable blocks of code that perform specific tasks.
Example: Adding Two Numbers
String Functions in C++: Manipulating Text
C++ provides several built-in functions for string manipulation. Include the `` header.
-
length()
Function: Returns the length of the string. -
substr()
Function: Extracts a substring from a string. -
append()
Function: Appends one string to another. -
compare()
Function: Compares two strings. -
empty()
Function: Checks if a string is empty.
Object-Oriented Programming (OOP) Concepts in C++
1. Class
A class is a blueprint for creating objects, defining their properties (data members) and behaviors (member functions).
2. Object
An object is an instance of a class. It is a real-world entity that has properties and behaviors.
3. Polymorphism
Polymorphism means "many forms." It allows objects of different classes to respond differently to the same function call.
Types of Polymorphism
- Compile-time Polymorphism
- Runtime Polymorphism
Compile-time Polymorphism can be achieved using:
- Operator overloading
- Function overloading
Runtime Polymorphism can be achieved using:
- Function overriding
- Virtual Functions
4. Inheritance
Inheritance allows a class (child class) to inherit properties and behaviors from another class (parent class). This promotes code reusability.
Types of Inheritance:
- Single Inheritance: A derived class inherits from a single base class.
- Multiple Inheritance: A derived class inherits from multiple base classes.
- Multilevel Inheritance: A derived class inherits from another derived class.
- Hierarchical Inheritance: When