CPP (c++) is the most powerful, most useful, most graceful, and most widely used programming language in the world.
This is a fast cpp language programming guide, many things are not explained too enough, just try it again and again, modify and practice more.
Back Index: Learn CPP
sudo pacman
-S
gcc
sudo apt
install g++
code: hello.cpp
#include <iostream> int main() { std::cout << "Hello, World!" << std::endl; }
run
.
Linux(KaOS/Kubuntu/Ubuntu/etc):
$ vim hello.cpp $ g++ hello.cpp -o hello $ ./hello Hello, World!
FreeBSD
$ vim hello.cpp $ clang++ hello.cpp -o hello $ ./hello Hello, World!
Alt Editors: kakoune, cpeditor, emacs, etc.
In the following context, I will not mention how to install and how to compile any more.
Code: output.cpp
#include <iostream> int main() { std::cout << "Hello, World!" << std::endl; std::cout << 9; std::cout << '\n'; std::cout << 1.553; std::cout << "\n"; std::cout << "This is some text.\n"; }
std::cout
and std::endl
are defined in that file! That's
enough to know now!
I will not explain them, you can try, compile, modify and practice them, very simple.
Code: int.cpp
#include <iostream> int main() { int x = 3; int y = 4; int z = x+y; std::cout << x << " + " << y << " = " << z << std::endl; }
Basic Float: float
Double Precision Float: double
Code: float.cpp
#include <iostream> int main() { float x = 1.25; float y = 3.33; float z = x*y; double a = 131.145; double b = 2.1; double c = a/b; std::cout << z << '\n' << c << "\n"; }
What is string? Because some data are not math numbers, they are text, we can call them string.
Code: std-string.cpp
#include <iostream> #include <string> int main() { std::string name = "John Smith"; std::cout << name << std::endl; }
Do you notice the #include <string> line? Yes, std::string is defined in that file: string.
Code: input.cpp
#include <iostream> #include <string> int main() { int x; std::cout << "Please input an integer: "; std::cin >> x; std::cout << "Your integer is " << x << std::endl; std::string text; std::cout << "Please input some text: "; std::cin >> text; std::cout << "Your text is " << text << std::endl; }
Quick Explain
Amazing! Isn't it? You have std::cout and std::cin now. And you have << and >> now.
Have you found the problem of std::cin? If your input text is Hello World!, the following output will be Your text is Hello . Where did my World! go? Yeah, if the input text has a space between them, only the first part before the first space are received, the rest will be assigned to the rest variables of your program, however your program might not define more variables.
Then please use std::getline to read the whole line input.
Code: std-getline.cpp
#include <iostream> #include <string> int main() { std::string text; std::cout << "Please input some text: "; std::getline(std::cin, text); std::cout << "Your text is " << text << std::endl; }
--- - >
---
1. Bird cries. - Which bird is crying? We don't know. It means all birds can cry, all birds have the feature of crying. So, Bird is a class.
2. A bird is crying. - Yes, we might notice that a bird here is crying. So, bird is an object.
Let's start simple object-oriented code.
Code: oop.cpp
#include <iostream> #include <string> class Bird { private: // Property std::string name; public: // Constructor Bird(std::string aName) { name = aName; } // Method void cry() { std::cout << "I am a bird." << std::endl; std::cout << "My name is " << name << std::endl; std::cout << "I am crying." << std::endl; std::cout << std::endl; } // Destructor ~Bird() { } }; int main() { Bird lilith{"Lilith"}; lilith.cry(); Bird alice{"Alice"}; alice.cry(); }
Compile and Run the Code:
I am a bird. My name is Lilith I am crying. I am a bird. My name is Alice I am crying.
What is template?
Let's start this story simply:
There are green bird, black bird, and purple bird in the world.
We can not just use only Bird to define them.
We have to define them using Green Bird, Black Bird, and Purple Bird.
But they are still Bird.
Define Green:
class Green {};
Define Black:
class Black {};
Define Purple:
class Purple {};
Define template Bird, it can be shadered with different color:
template <typename Type> class Bird { };
Using different Bird:
Bird<Green> greenBird; Bird<Black> blackBird; Bird<Purple> purpleBird;
Can you assemble the code piece to a whole complete program and add some methods now? Try it.
Code: simple-template.cpp
#include <iostream> class Green {}; class Black {}; class Purple {}; template <typename Color> class Bird { private: Color color; public: // Constructor. Bird() { std::cout << "A bird is created." << std::endl; } // Destructor. ~Bird() { std::cout << "A bird disappeared!" << std::endl; } }; int main() { Bird<Green> greenBird; Bird<Black> blackBird; Bird<Purple> purpleBird; }
template-add-method.cpp
#include <iostream> #include <string> class Green { public: std::string getColor() { return "Green"; } }; class Black { public: std::string getColor() { return "Black"; } }; class Purple { public: std::string getColor() { return "Purple"; } }; template <typename Color> class Bird { private: Color color; std::string name; public: // Constructor: set this bird name. Bird(std::string aName) { name = aName; } // Destructor: do nothing here. ~Bird() {} // Method: Cry void cry() { std::cout << "I am a bird, my name is " << name << ", my color is " << color.getColor() << std::endl; } }; int main() { Bird<Green> bob{"Bob"}; bob.cry(); Bird<Black> lilith{"Lilith"}; lilith.cry(); Bird<Purple> alice{"Alice"}; alice.cry(); }
Compile and Run the Code:
I am a bird, my name is Bob, my color is Green I am a bird, my name is Lilith, my color is Black I am a bird, my name is Alice, my color is Purple
If a variable has its own name, you can give it an alias name too, which is called reference in cpp.
int x = 11; int & y = x; // y is reference to x now. x = 13; // y becomes 13 too. y = 17; // x becomes 17 too.
And the variables can be set to constant:
const int x = 13; // x = 19; // ERORR: x is constant, you can not change it any more.
Constant and reference can be used together, to be const reference:
int x = 25; const int & y = x;
Exception Basic Framework:
// catch by value copy. BAD
try { throw Error_Type_Value; } catch (Error_Type value) { }
// catch by reference. GOOD
try { throw Error_Type_Value; } catch (Error_Type & value) { // Reference catch }
Example 1: throw integer
#include <iostream> int main() { try { throw 21; } catch (int value) { std::cout << "I catch: " << value << std::endl; } }
However, you'd better use reference in catch statement anywhere, to avoid exception memory copy:
#include <iostream> int main() { try { throw 21; } catch (int & value) { // reference catch std::cout << "I catch: " << value << std::endl; } }
Example 2: throw std::string
#include <iostream> #include <string> int main() { try { std::string msg = "Error Code"; throw msg; } catch (std::string & value2) { std::cout << "I catch: " << value2 << std::endl; } }
Example 3: throw object
#include <iostream> class Swan { public: void say() { std::cout << "I am a swan!" << std::endl; } }; int main() { try { Swan swan; throw swan; } catch (Swan & swan) { std::cout << "I catch: "; swan.say(); } }
Example 4: Unkown Catch
The program might not guarantee every exception can be caught. Using three dots to catch anything, but the msg is unknown.
#include <iostream> int main() { try { throw "Can you catch me?"; } catch (...) { std::cout << "I catch unknown." << std::endl; } }
Example 5: System Exception: std::exception and std::runtime_error
#include <iostream> int main() { try { throw std::runtime_error{"An error occured."}; } catch (std::exception & exc) { std::cout << "Exception: " << exc.what() << std::endl; } }
Have you noticed that the prefix std::? Yeah, it is namespace. Namespace can be used to avoid name conflicts.
How to define namespace for myself:
Code: namespace.cpp
#include <iostream> namespace myns1 { class Hello { public: Hello() { std::cout << "A hello is created!\n"; } ~Hello() { std::cout << "A hello disappeared!" << std::endl; } void greeting() { std::cout << "Hello, World!" << std::endl; } }; } int main() { myns1::Hello hello1; hello1.greeting(); }
void hello() { std::cout << "Hello!"; } std::string world() { return "World!"; }
auto hello = [] () { std::cout << "Hello!"; }; auto world = [] { return "World!"; };
Example Code: functional.cpp
#include <iostream> #include <string> // First Functional auto fn = [] (int x, int y) { int z = x+y; std::cout << "Sum:" << z << std::endl; return z; }; int main() { // Call first functional auto result = fn(3, 4); std::cout << "Result: " << result << std::endl; // Second Functional auto func = [] (int a, int b, auto c) { std::cout << a << ' ' << b << ' ' << c << std::endl; }; // Call second functional func(1, 2, 3.4); }
if
int x = 3; if (x == 3) { std::cout << "OK!" << std::endl; }
switch
int x = 3; switch (x) { case 1: std::cout << "one" << std::endl; break; case 2: std::cout << "two" << std::endl; break; case 3: std::cout << "three" << std::endl; break; default: break; }
for Loop
for (int i=0; i<10; ++i) { std::cout << i << std::endl; }
Please notice the evaluate order:
while Loop
int i=0; while (i<10) { std::cout << i << std::endl; ++i; }
do-while Loop
int i=0; do { std::cout << i << std::endl; ++i; } while (i<10);
The difference between while and do-while:
Different cpp compilers have different ways to enable latest c++ standard. For example, gcc and clang:
g++ your-code.cpp -std=c++2b -o your-program
clang++ your-code.cpp -std=c++2b -o your-program
These cpp standards are valid currently:
The most important part of using cpp (c++) is using libraries. The language itself can not do everything for you, not possible, not necessary, and not responsible. You need libraries to achieve your goals.
Stanard library api commonly starts with std:: namespace prefix. And they always have no header filename suffix.
The best place to look up standard library api is https://en.cppreference.com
std::vector
std::vector is a raid of continuous memory storage data. It is a more safe and more easy to use array.
#include <iostream> #include <vector> int main() { std::vector<int> v1{1, 2, 3, 4, 5}; for (int i=0; i<v1.size(); ++i) std::cout << v1[i] << ' '; std::cout << std::endl; std::vector<float> v2{1.1, 2.2, 3.3}; for (int i=0; i<v2.size(); ++i) std::cout << v2[i] << ' '; std::cout << std::endl; std::vector<int> v3{5, 4, 3, 2, 1}; v3.push_back(0); for (auto & x: v3) std::cout << x << ' '; std::cout << std::endl; }
std::queue
You can imagine a queue of man there, only the front man can take what he want and leave, and the new comer must stand at the backend. std::queue is such a structure that allows data to be pushed back and popped front.
Some Useful Methods:
#include <queue> #include <iostream> int main() { std::queue<int> q1; for (int i=4; i<9; ++i) q1.push(i); while (!q1.empty()) { std::cout << q1.front() << ' '; q1.pop(); } std::cout << std::endl; }
Result:
4 5 6 7 8
std::stack
std::stack is a data structure that allows data to be pushed at the top, and popped at the top.
Some Useful Methods:
#include <stack> #include <iostream> int main() { std::stack<int> stack; for (int i=4; i<9; ++i) { stack.push(i); } while (!stack.empty()) { std::cout << stack.top() << ' '; stack.pop(); } std::cout << std::endl; }
Boost is the candidate standard libraries of cpp (c++), many new features of cpp comes from boost.
The official website of boost libraries is https://www.boost.org , you can download, install and read documents from the website. And most operating system distros have already installed it.
boost::asio and boost::beast
boost::asio and boost::beast are the candidate standard networking libraries of cpp.
#include <boost/asio.hpp> #include <iostream> namespace asio = boost::asio; int main() try { asio::io_context ioContext; ioContext.post( [] { std::cout << "Hello "; } ); asio::io_context::strand strand{ioContext}; strand.post( [] { std::cout << "World "; } ); ioContext.run(); } catch (std::exception & exc) { std::cout << "Asio Exception: " << exc.what() << std::endl; }
Irrlicht is a high performance and high quality 3D engine that can create games and GUI applications.
Irrlicht official homepage: https://irrlicht.sourceforge.io
Using irrlicht to open a blue GUI window:
#include <irrlicht.h> int main() { irr::IrrlichtDevice * device = irr::createDevice( irr::video::EDT_BURNINGSVIDEO, irr::core::dimension2du{1280, 720}, 32, false, true, true, nullptr ); irr::video::IVideoDriver * driver = device->getVideoDriver(); irr::gui::IGUIEnvironment * igui = device->getGUIEnvironment(); irr::scene::ISceneManager * smgr = device->getSceneManager(); while (device->run()) { driver->beginScene( irr::video::ECBF_COLOR | irr::video::ECBF_DEPTH, irr::video::SColor{0xff3765a2} ); smgr->drawAll(); igui->drawAll(); driver->endScene(); } }