A
A
Artem2016-07-03 17:04:16
OOP
Artem, 2016-07-03 17:04:16

Where and when is it correct to use extern?

Actually, subject.
The question arose from the situation. There is a class whose methods use an instance of another class. In each method, I created this instance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mercury13, 2016-07-03
@proudmore

The purpose of extern is the only one. We say that this variable is not in this compilation unit, but don't worry, it is in another one and the linker will sublink it.
In fact, it is an extern static field of the class. This decision was made by Stroustrup for a simple reason: the class definition can flash several times in different compilation units, and the variable definition must be one per program.
If your code does not work without extern, it means that a global variable called client was found somewhere, and for the webmaster to work correctly, it was necessary to contact this client of ours. In fact, a very fancy way to create a static field.
Thus, you have three options.
1. If there is only one Ethernet client for all webmasters, you need a static field.

// HEADER
class WebMaster {
public:
    WebMaster();
    bool connect_open();
private:
    static EthernetClient client;
}

// CPP
EthernetClient WebMaster::client;

However, this option is extremely unlikely.
2. Most likely, you have one webmaster - one client and, probably, you need a regular non-static field.
class WebMaster {
public:
    WebMaster();
    bool connect_open();
private:
    EthernetClient client;
}

3. If we have to bind masters to clients, we have to use pointers and links. In its simplest form...
// HEADER
class WebMaster {
public:
    WebMaster(EthernetClient& aClient);
    bool connect_open();
private:
    EthernetClient& client;
}

// CPP
WebMaster::WebMaster(EthernetClient& aClient) : client(aClient) {}

...
EthernetClient client;
WebMaster webmaster(client);

S
sitev_ru, 2016-07-03
@sitev_ru

class WebMaster {
public:
    EthernetClient client;
    WebMaster();
}

WebMaster::WebMaster() {
}

bool WebMaster::connect_open() {
    byte addr[4]= {xx,xx,xx,xx};
    if (client.connect(addr, 80)) {
      return true;
    }
    else{
      return false;
    }
}

M
mamkaololosha, 2016-07-03
@mamkaololosha

Strange decision. Why not instantiate the class internally? Or inherit from it?
Or

EthernetClient client;
WebMaster master1;
WebMaster master2;
master1.setClient(client);
master2.setClient(client);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question