C++ is a superset of C. Most syntax are same.
Data Type
int myNum = 5; // Integer (whole number) float myFloatNum = 5.99; // Floating point number double myDoubleNum = 9.98; // Floating point number char myLetter = 'D'; // Character bool myBoolean = true; // Boolean string myText = "Hello"; // String
Data Type | Size | Description |
bool | 1 byte | Stores true or false values |
char | 1 byte | Stores a single character/letter/number, or ASCII values |
int | 2 or 4 bytes | Stores whole numbers, without decimals |
float | 4 bytes | Stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7 decimal digits |
double | 8 bytes | Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits |
String is not a built-in data type, so to use it should include the
<string> library:#include <iostream> #include <string> using namespace std; int main() { // Write C++ code here string greeting = "Hello"; std::cout << greeting; return 0; }
Two ways for string concatenation:
+operator:
string firstName = "John"; string lastName = "Doe"; string fullName = firstName + " " + lastName; cout << fullName;
Attention: string + string = string, number + number = number, but string + number ⇒ error
appendmethod(string is an object actually):
string firstName = "John "; string lastName = "Doe"; string fullName = firstName.append(lastName); cout << fullName;
auto keywordauto will detect the type and assign it to the variable:auto x = 5; // x is automatically treated as int`1
Function
function overloading:
int myFunction(int x) float myFunction(float x) double myFunction(double x, double y)
Lambda
syntax:
[capture] (parameters) { code };
Basic use:
int main() { auto message = []() { cout << "Hello World!\n"; }; message(); return 0; }
Passing lambdas to functions:
#include <iostream> #include <functional> // Needed for std::function using namespace std; // A function that takes another function as parameter void myFunction(function<void()> func) { func(); func(); } int main() { auto message = []() { cout << "Hello World!\n"; }; myFunction(message); return 0; }
Capture clause
[] int main() { int x = 10; auto show = [x]() { cout << x; }; show(); return 0; }
[x] will copy the value of x, and [&x] can refer the latest value of xClass
Method
Two ways to define methods in Class:
- Inside class definition
- Outside class definition
#include <iostream> #include <string> using namespace std; class Car { public: string name; // Inside void start() { cout << "Start the car " << this->name << '\n'; }; void stop(); }; // Outside void Car::stop() { cout << "Stop the car " << this->name << '\n'; } int main() { Car myCar; myCar.name = "BMW"; myCar.start(); myCar.stop(); return 0; }
Access specifiers
public- members are accessible from outside the class
private- members cannot be accessed (or viewed) from outside the class
protected- members cannot be accessed from outside the class; however, they can be accessed in inherited classes.
Friend Function
Friend functions can access private methods in one Class.
#include <iostream> using namespace std; class Employee { private: int salary; public: Employee(int s) { salary = s; } // Declare the friend function friend void displaySalary(Employee emp); }; void displaySalary(Employee emp) { cout << "Salary: " << emp.salary << '\n'; } int main() { Employee emp = Employee(5000); displaySalary(emp); return 0; }
Virtual Method
A virtual method indicates it can be overridden by a derived class.
Without virtual method:
#include <iostream> using namespace std; class Animal { public: void sound() { cout << "Animal sound" << '\n'; } }; class Dog: public Animal { public: void sound() { cout << "Dog bow bow" << '\n'; } }; int main() { Animal *a; Dog d; a = &d; a->sound(); // Animal sound return 0; }
With virtual method:
#include <iostream> using namespace std; class Animal { public: virtual void sound() { cout << "Animal sound" << '\n'; } }; class Dog: public Animal { public: // `override` keyword can be optional void sound() override { cout << "Dog bow bow" << '\n'; } }; int main() { Animal *a; Dog d; a = &d; a->sound(); // Dog bow bow return 0; }
->
Pointers can use
-> operator to access members (like attributes or methods) in an object.#include <iostream> using namespace std; class Animal { public: void sound() { cout << "Animal sound" << '\n'; } }; int main() { Animal* a = new Animal(); // Both are same a->sound(); (*a).sound(); return 0; }
Template
A template defines a dynamic data type used for functions and classes.
- Function template
#include <iostream> using namespace std; template <typename T> T add(T a, T b) { return a + b; } int main() { std::cout << add<float>(1.2, 7.3); return 0; }
- Class template
#include <iostream> #include <string> using namespace std; template <typename T> class Box { public: T value; Box(T v) { value = v; } void show() { cout << "The value is " << value << '\n'; } }; int main() { Box<int> intBox(50); Box<string> strBox("HELLO"); intBox.show(); // The value is 50 strBox.show(); // The value is HELLO return 0; }
Error
Exception
C++ supports
try/catch/throw :try { int age = 15; if (age >= 18) { cout << "Access granted - you are old enough."; } else { throw (age); } } catch (int myNum) { cout << "Access denied - You must be at least 18 years old.\n"; cout << "Age is: " << myNum; }
Use
... to handle any type:try { int age = 15; if (age >= 18) { cout << "Access granted - you are old enough."; } else { throw 505; } } catch (...) { cout << "Access denied - You must be at least 18 years old.\n"; }
Data Structure
STL: Standard Template Library
Data Structure | Description |
Stores elements like an array but can dynamically change in size. Adding and removing of elements are usually done at the end. Elements can be accessed by index. | |
Stores elements sequentially, where each element is connected to the next. Adding and removing of elements can be done at both ends. Not accessible by index. | |
Stores elements in a specific order, called LIFO (Last In, First Out), where elements can only be added and removed from the top. Not accessible by index. | |
Stores elements in a specific order, called FIFO (First In, First Out), where elements are added at the end and removed from the front. Not accessible by index. | |
Stores elements in a double-ended queue, where elements can be added and removed from both ends. Elements can be accessed by index. | |
Stores unique elements. Not accessible by index. | |
Stores elements in "key/value" pairs. Accessible by keys (not by index). |
Namespace
A namespace can group variables to avoid name conflicts.
#include <iostream> namespace MyNamespace { int x = 42; } int main() { int x = 30; std::cout << "MyNamespace x is: " << MyNamespace::x << '\n'; // MyNamespace x is: 42 std::cout << "Main() x is :" << x << '\n'; // Main() x is :30 return 0; }
using namespace to simplify the usage:#include <iostream> namespace MyNamespace { int x = 42; int y = 90; int z = 100; } using namespace MyNamespace; int main() { std::cout << "MyNamespace x is: " << x << '\n'; std::cout << "MyNamespace y is: " << y << '\n'; std::cout << "MyNamespace z is: " << z << '\n'; return 0; }
cout, cin , and endl belong to std (Standard). There are also two ways to use them:using namespace std;
std::cout
Prefer the second way in large programs to prevent naming conflicts.