C++
C++ is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C programming language, or βC with Classesβ. The language has expanded significantly over time, and modern C++ has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
Resources
Getting start
To start programming in C++, you need to have a compiler installed on your computer. The most popular compiler is g++
, which is part of the GNU Compiler Collection (GCC).
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World!" << endl;
return 0;
}
g++ -o app main.cpp && ./app
Topics
- Primitive Types
- Operators
- Strings
- Arrays
- Pointers
- Control Structures
- Loops
- Structs
- Enum
- Functions
- Classes
- Inheritance
- Error Handling
- Namespace, using, #include, #define, #ifndef, #endif
Primitive types
int a = 10;
float b = 10.5;
double c = 10.5;
char d = 'A';
bool e = true;
string f = "Hello World";
Constants
const double pi = 3.14159265358979323846;
const char newline = '\n';
Operators
int a = 10;
int b = 20;
// Arithmetic operators
int c = a + b; // 30
int d = a - b; // -10
int e = a * b; // 200
int f = a / b; // 0
int g = a % b; // 10
// Relational operators
bool h = a == b; // false
bool i = a != b; // true
bool j = a > b; // false
bool k = a < b; // true
bool l = a >= b; // false
bool m = a <= b; // true
// Logical operators
bool n = true && false; // false
bool o = true || false; // true
bool p = !true; // false
// Bitwise operators
int q = a & b; // 0
int r = a | b; // 30
int s = a ^ b; // 30
int t = ~a; // -11
int u = a << 2; // 40
int v = a >> 2; // 2
// Assignment operators
a += b; // 30
a -= b; // 10
a *= b; // 200
a /= b; // 10
a %= b; // 10
a &= b; // 0
a |= b; // 30
a ^= b; // 30
a <<= 2; // 40
a >>= 2; // 10
// Misc operators
int w = sizeof(a); // 4
int x = &a; // 0x7ffebc3b3b4c
int y = *x; // 10
// Conditional operator
int z = (a > b) ? a : b; // 20
// Comma operator
int aa = (a++, b++); // 20
// Pointer operator
int *ab = &a;
int ac = *ab;
Strings
string str1 = "Hello";
string str2 = "World";
string str3 = str1 + " " + str2; // Hello World
string str4 = str1.append(" World"); // Hello World
string str5 = str1.substr(0, 5); // Hello
int str6 = str1.length(); // 11
string str7 = "Hello World";
str7[0] = 'J'; // Jello World
string str8 = "Hello World";
str8.at(0) = 'J'; // Jello World
string str9 = "Hello World";
str9.insert(5, "C++"); // Hello C++World
string str10 = "Hello World";
str10.erase(5, 5); // Hello
string str11 = "Hello World";
if (str11.find("World") != string::npos)
{
cout << "Found" << endl;
}
else
{
cout << "Not found" << endl;
}
Arrays
int arr1[5] = {1, 2, 3, 4, 5};
// accessing elements
int a = arr1[0]; // 1
int b = arr1[1]; // 2
int c = arr1[2]; // 3
// modifying elements
arr1[0] = 10;
// multidimensional arrays
int arr2[2][3] = {{1, 2, 3}, {4, 5, 6}};
// multidimensional arrays: accessing elements
int d = arr2[0][0]; // 1
int e = arr2[0][1]; // 2
// multidimensional arrays: modifying elements
arr2[0][0] = 10;
// array functions
int arr3[5] = {1, 2, 3, 4, 5};
sort(arr3, arr3 + 5);
reverse(arr3, arr3 + 5);
fill(arr3, arr3 + 5, 0);
// array size
int size = sizeof(arr3) / sizeof(arr3[0]);
// array copy
int arr4[5];
copy(arr3, arr3 + 5, arr4);
// array fill
fill(arr4, arr4 + 5, 0);
Casting
int a = 10;
float b = 10.5;
double c = 10.5;
// implicit casting
float d = a; // 10.0
double e = a; // 10.0
double f = b; // 10.5
// explicit casting
int g = (int)b; // 10
int h = (int)c; // 10
float i = (float)a; // 10.0
float j = (float)c; // 10.5
double k = (double)a; // 10.0
double l = (double)b; // 10.5
// static casting
int m = static_cast<int>(b); // 10
int n = static_cast<int>(c); // 10
float o = static_cast<float>(a); // 10.0
float p = static_cast<float>(c); // 10.5
double q = static_cast<double>(a); // 10.0
double r = static_cast<double>(b); // 10.5
Pointers
int a = 10; // variable
int *b = &a; // pointer
cout << *b << endl; // 10
cout << b << endl; // 0x7ffebc3b3b4c
Control structures
int a = 10;
int b = 20;
// if statement
if (a > b)
{
cout << "a is greater than b" << endl;
}
else
{
cout << "a is less than or equal to b" << endl;
}
// switch statement
int c = 2;
switch (c)
{
case 1:
cout << "Case 1" << endl;
break;
case 2:
cout << "Case 2" << endl;
break;
default:
cout << "Default case" << endl;
}
Loops
// while loop
int a = 0;
while (a < 5)
{
cout << a << endl;
a++;
}
// do-while loop
int b = 0;
do
{
cout << b << endl;
b++;
} while (b < 5);
// for loop
for (int c = 0; c < 5; c++)
{
cout << c << endl;
}
// range-based for loop
int arr[5] = {1, 2, 3, 4, 5};
for (int x : arr)
{
cout << x << endl;
}
Structs
// struct
struct Point
{
// data members
int x;
int y;
// constructor
Point(int x, int y)
{
this->x = x;
this->y = y;
}
// constructor overloading
Point()
{
x = 0;
y = 0;
}
// member function
void increment()
{
x++;
y++;
}
// member function
void decrement()
{
x--;
y--;
}
// member function
void print()
{
cout << "Point(" << x << ", " << y << ")" << endl;
}
};
// usage
int main()
{
Point p1(1, 2);
p1.increment();
p1.print();
Point p2;
p2.decrement();
p2.print();
return 0;
}
Enum
// enum
enum Color
{
RED,
GREEN,
BLUE
};
// enum for weeks
enum Week
{
MONDAY = 1,
TUESDAY = 2,
WEDNESDAY = 3,
THURSDAY = 4,
FRIDAY = 5,
SATURDAY = 6,
SUNDAY = 7
};
int main()
{
Color b = BLUE;
cout << b << endl;
Color r = RED;
cout << r << endl;
Week monday = MONDAY;
// increment monday
monday = static_cast<Week>(monday + 1);
cout << monday << endl; // 2 - tuesday
return 0;
}
Functions
// simple function
void printHello()
{
cout << "Hello" << endl;
}
// function with parameters
void printName(string name)
{
cout << "Hello " << name << endl;
}
// function with return value
int add(int a, int b)
{
return a + b;
}
// function with default parameters
void printNumber(int number = 10)
{
cout << number << endl;
}
// function overloading
int add(int a, int b)
{
return a + b;
}
float add(float a, float b)
{
return a + b;
}
double add(double a, double b)
{
return a + b;
}
Classes
// class point
class Point
{
// private members
private:
int x, y;
// public members
public:
// default constructor
Point() : x(0), y(0)
{
cout << "Default Point constructor called" << endl;
}
// parameterized constructor
Point(int x, int y) : x(x), y(y)
{
cout << "Point constructor called" << endl;
}
// getters
int getX() { return x; }
int getY() { return y; }
// setters
void setX(int x) { this->x = x; }
void setY(int y) { this->y = y; }
// operator overloading
Point operator+(Point const &obj)
{
Point res;
res.x = x + obj.x;
res.y = y + obj.y;
return res;
}
// destructor
~Point()
{
cout << "Point destructor called" << endl;
}
};
// usage
int main()
{
Point p1;
Point p2(10, 20);
cout << "p1: " << p1.getX() << ", " << p1.getY() << endl;
cout << "p2: " << p2.getX() << ", " << p2.getY() << endl;
return 0;
}
Inheritance
class Person
{
public:
string name;
int age;
Person(string name, int age)
{
this->name = name;
this->age = age;
}
};
class Hero : public Person
{
public:
int level;
Hero(string name, int age, int level) : Person(name, age)
{
this->level = level;
}
};
int main()
{
Hero hero("John", 25, 10);
cout << hero.name << endl;
cout << hero.age << endl;
cout << hero.level << endl;
return 0;
}
Error Handling
// simple try catch block
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
// nested try catch block
try
{
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
// rethrowing an exception
try
{
try
{
throw 20;
}e
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << '\n';
throw; // rethrowing the exception
}
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
// catch all exceptions
try
{
throw 'a';
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
catch (char e)
{
cout << "An exception occurred. Exception char " << e << '\n';
}
catch (...)
{
cout << "An exception occurred. Exception unknown" << '\n';
}
// standard exceptions
try
{
throw runtime_error("runtime error");
}
catch (exception &e)
{
cout << "Standard exception: " << e.what() << '\n';
}
Custom Exception
#include <iostream>
using namespace std;
// custom exception
class MyException : public exception
{
public:
virtual const char *what() const throw()
{
return "Something bad happened!";
}
};
int main()
{
try
{
throw MyException();
}
catch (MyException &e)
{
cout << e.what() << endl;
}
return 0;
}
namespace, using, #include, #define, #ifndef, #endif
lib.h
#ifndef _LIB_CALC_
#define _LIB_CALC_
namespace lib
{
class Calc
{
public:
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
};
}
#endif
main.cpp
#include <iostream>
#include "./lib.h"
using namespace std;
using namespace lib;
int main(int argc, char const *argv[])
{
Calc c;
cout << c.add(1, 2) << endl;
cout << c.sub(1, 2) << endl;
}