Skip to content

03. Object Oriented II

Ziviani edited this page Mar 21, 2016 · 3 revisions

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 instantiated, it has a life cycle, and the object will be destroyed sometime. Methods exists to change or read the instance properties (state) during that time. Thus, we already know that we need to worry about some things about our classes:

    • what it should do when instantiated?
    • what it should do when destroyed?
    • 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++.

image

#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;
};

That C++ class implementation doesn't look exactly like the class in that diagram, but why? I have an idea, but I think we need to make a trip to the C++'s ❤️ :) to find a robust response.