神刀安全网

Modern C++ from ground up

What’s a C++ class?

C++ classes are nothing more than user defined data. It’s composed by fundamental types like integer, chars, float numbers and/or other user defined objects; these types are called member variables in C++ but I like to name them ‘properties’.

In a C++ class it’s also possible to implement functions, usually named methods. Once a variable of that class is defined we say that such class was instantiated, in other words, an object of that class was created.

As soon as your class is instanced, it has a life cycle that will be destroyed sometime. So, methods exists to change or read the instance properties during the time the instance is alive. Thus, we already know that we need to worry about some things about our classes:

  1. * what it should do when instantiated?
  2. * what it should do when destroyed?
  3. * what it should do when users want to change the class state? (change properties)

So, let’s imagine the following scenario, we have a simple class diagram and we want to represent such class in C++.

Modern C++ from ground up

#include <array> #include <string>  const int MAX_CONNECTIONS = 10;  class server {     public:         // 1. construct without parameters         server();         // 1. construct with parameters         server(std::string address, std::string port);         // 2. take care of used resources when the instance is destroyed         virtual ~server();          // 3. remove code that make no sense to our server (we will see them in future) but         //    this will avoid code like this:         //    server s1("localhost", "123456");         //    server s2;         //    s2 = s1; <= wrong!         server (const server &other) = delete;         server(server &&other) = delete;         server &operator=(const server &other) = delete;         server &operator=(server &&other) = delete;          // 3. check is server instance is running         bool status() const noexcept;          // 3. change the server state to shutdown         void shutdown();      private:         // helper methods, accessible inside only         void initialize() noexcept;         void listen() noexcept;      private:         // properties are private, only our public methods will let them be         // writeable/readable outsite         bool _is_running;         std::string _addr;         std::string _port;         int socket_server;         std::array<int, MAX_CONNECTIONS> current_connections; };

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Modern C++ from ground up

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮