cpp/c++ object oriented programming
cpp/c++ object oriented programming treats the real world entities set as a whole concept, and then creates many objects according that concept.
The concept of the entities set is called class in c++, by keyword class .
Every entity created by c++ class is called object.
"A is derived from B"
.
private, protected, public
,
the sensitive data can be made hidden by private or protected .
Save code as chat-robot.cpp
#include <iostream> #include <string> // This is a comment line. class chat_robot { public: void speak() { std::cout << "Hello, I am a chat robot, please talk to me." << std::endl; } }; int main() { chat_robot robot_no_1; robot_no_1.speak(); auto robot_no_2 = chat_robot{}; robot_no_2.speak(); }
Compile and run:
$ g++ chat-robot.cpp -std=c++23 -o chat-robot $ ./chat-robot Hello, I am a chat robot, please talk to me. Hello, I am a chat robot, please talk to me.
You can see that, the program has a class, its name is chat_robot .
The class chat_robot has a method: speak .
Object definition, can be also called object creation.
chat_robot robot_no_1; auto robot_no_2 = chat_robot{};
In this example, two ways are used to create object of the class chat_robot as above. Two objects are created: robot_no_1, and robot_no_2 .
The word auto is very powerful and simple in c++ .
robot_no_1.speak();
The above code shows how to call the method .speak() with the object robot_no_1 .
You might read many information about c++ class from this article, but please do not feel stress. You only need to focus on the features that the example shows, and other information can be ignored and will be explained in next articles. As the example demonstrates, you only need to focus on four points from this article:
And at last, please care and remember the word auto, you do not have to understand auto now .
Written on Aug 04, 2024
c++ std::exception:
std::cout.write(err.data(), err.size());
std::cout << std::endl;
caught:
=================================== # The c++ programming language. # # # # Join c++ Discord: yZcauUAUyC # # Deck # ===================================