C++ is a cross-platform language that can be used to create high-performance applications.
C++ was developed by Bjarne Stroustrup, as an extension to the C language.
C++ gives programmers a high level of control over system resources and memory.
The language was updated 4 major times in 2011, 2014, 2017, and 2020 to C++11, C++14, C++17, C++20.
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
cout << "Hello World!";
cout << "Hello World!" << endl;
// This is a comment
/* The code below will print the words Hello World
to the screen, and it is amazing */
type variableName = value;
int myNum = 15;
cout << myNum;
const int myNum = 15; // myNum will always be 15
cin >> x; // Get user input from the keyboard
Data Type | Size | Description |
---|---|---|
boolean |
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 |
Operator | Name | Description | Example |
---|---|---|---|
+ | Addition | Adds together two values | x + y |
- | Subtraction | Subtracts one value from another | x - y |
* | Multiplication | Multiplies two values | x * y |
/ | Division | Divides one value by another | x / y |
% | Modulus | Returns the division remainder | x % y |
++ | Increment | Increases the value of a variable by 1 | ++x |
-- | Decrement | Decreases the value of a variable by 1 | --x |
Operator | Example | Same As |
---|---|---|
= | x = 5 | x = 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
%= | x %= 3 | x = x % 3 |
&= | x &= 3 | x = x & 3 |
|= | x |= 3 | x = x | 3 |
^= | x ^= 3 | x = x ^ 3 |
>>= | x >>= 3 | x = x >> 3 |
<<= | x <<= 3 | x = x << 3 |
Operator | Name | Example |
---|---|---|
== | Equal to | x == y |
!= | Not equal | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
Operator | Name | Description | Example |
---|---|---|---|
&& | Logical and | Returns true if both statements are true | x < 5 && x < 10 |
|| | Logical or | Returns true if one of the statements is true | x < 5 || x < 4 |
! | Logical not | Reverse the result, returns false if the result is true | !(x < 5 && x < 10) |
#include <string>
string greeting = "Hello";
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
cout << fullName;
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();
string myString = "Hello";
cout << myString[0];
// Outputs H
Escape character | Result | Description |
---|---|---|
\' | ' | Single quote |
\" | " | Double quote |
\\ | \ | Backslash |
Escape Character | Result |
---|---|
\n | New Line |
\t | Tab |
Function | Description |
---|---|
abs(x) | Returns the absolute value of x |
acos(x) | Returns the arccosine of x |
asin(x) | Returns the arcsine of x |
atan(x) | Returns the arctangent of x |
cbrt(x) | Returns the cube root of x |
ceil(x) | Returns the value of x rounded up to its nearest integer |
cos(x) | Returns the cosine of x |
cosh(x) | Returns the hyperbolic cosine of x |
exp(x) | Returns the value of Ex |
expm1(x) | Returns ex -1 |
fabs(x) | Returns the absolute value of a floating x |
fdim(x, y) | Returns the positive difference between x and y |
floor(x) | Returns the value of x rounded down to its nearest integer |
hypot(x, y) | Returns sqrt(x2 +y2) without intermediate overflow or underflow |
fma(x, y, z) | Returns x*y+z without losing precision |
fmax(x, y) | Returns the highest value of a floating x and y |
fmin(x, y) | Returns the lowest value of a floating x and y |
fmod(x, y) | Returns the floating point remainder of x/y |
pow(x, y) | Returns the value of x to the power of y |
sin(x) | Returns the sine of x (x is in radians) |
sinh(x) | Returns the hyperbolic sine of a double value |
tan(x) | Returns the tangent of an angle |
tanh(x) | Returns the hyperbolic tangent of a double value |
#include <cmath>
cout << max(5, 10);
cout << min(5, 10);
if (condition) {
// block of code to be executed if the condition is true
}
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
variable = (condition) ? expressionTrue : expressionFalse;
string result = (time < 18) ? "Good day." : "Good evening.";
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
while (condition) {
// code block to be executed
}
do {
// code block to be executed
}
while (condition);
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
for (type variableName : arrayName) {
// code block to be executed
}
break;
continue;
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
cars[0] = "Opel";
int myNumbers[5] = {10, 20, 30, 40, 50};
cout << sizeof(myNumbers);
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
cout << letters[0][2]; // Outputs "C"
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
cout << letters[i][j] << "\n";
}
}
struct { // Structure declaration
int myNum; // Member (int variable)
string myString; // Member (string variable)
} myStructure; // Structure variable
// Create a structure variable called myStructure
struct {
int myNum;
string myString;
} myStructure;// Assign values to members of myStructure
myStructure.myNum = 1;
myStructure.myString = "Hello World!";// Print members of myStructure
cout << myStructure.myNum << "\n";
cout << myStructure.myString << "\n";
struct {
int myNum;
string myString;
} myStruct1, myStruct2, myStruct3;
struct myDataType { // This structure is named "myDataType"
int myNum;
string myString;
};
myDataType myVar;
string food = "Pizza"; // food variable
string &meal = food; // reference to food
cout << food << "\n"; // Outputs Pizza
cout << meal << "\n"; // Outputs Pizza
string food = "Pizza"; // A food variable of type string cout << food; // Outputs the value of food (Pizza)
cout << &food; // Outputs the memory address of food (0x6dfed4)
string food = "Pizza"; // Variable declaration
string* ptr = &food; // Pointer declaration
// Reference: Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";
// Dereference: Output the value of food with the pointer (Pizza)
cout << *ptr << "\n";
// Change the value of the pointer
*ptr = "Hamburger";
// Output the new value of the pointer (Hamburger)
cout << *ptr << "\n";
// Output the new value of the food variable (Hamburger)
cout << food << "\n";
void myFunction() {
// code to be executed
}
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
// Function declaration
void myFunction();// The main method
int main() {
myFunction(); // call the function
return 0;
}// Function definition
void myFunction() {
cout << "I just got executed!";
}
void functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
void myFunction(string country = "Norway") {
cout << country << "\n";
}
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
// Sweden
// India
// Norway
// USA
int myFunction(int x) {
return 5 + x;
}
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}
int plusFunc(int x, int y) {
return x + y;
}
double plusFunc(double x, double y) {
return x + y;
}
int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
int main() {
int result = sum(10);
cout << result;
return 0;
}
Fruit
Apple
Banana
Mango
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main() {
MyClass myObj; // Create an object of MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text";
// Print attribute values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
class MyClass { // The class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};
// Constructor definition outside the class
Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}
int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
class MyClass { // The class
public: // Access specifier
// class members goes here
};
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
// Base class (parent)
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
// Derived class (child)
class MyChild: public MyClass {
};
// Derived class (grandchild)
class MyGrandChild: public MyChild {
};
int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}
// Base class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};// Another base class
class MyOtherClass {
public:
void myOtherFunction() {
cout << "Some content in another class." ;
}
};// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n";
}
};// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n";
}
};// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n";
}
};int main() {
Animal myAnimal;
Pig myPig;
Dog myDog; myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
Class | Description |
---|---|
ofstream |
Creates and writes to files |
ifstream |
Reads from files |
fstream |
A combination of ofstream and ifstream: creates, reads, and writes to files |
#include <iostream>
#include <fstream>
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "Files can be tricky, but it is fun enough!";
// Close the file
MyFile.close();
}
// Create a text string, which is used to output the text file
string myText;
// Read from the text file
ifstream MyReadFile("filename.txt");
// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}
// Close the file
MyReadFile.close();
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
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";
}