Chat freely about anything...

User avatar
By Ben Baron
#25610 Note that I'm an extremely new to C++. I'm wondering how this bit of code works:

Code: Select all    WiFiClient client;
    if (!client.connect(host, httpPort))
    {
        Serial.println("connection failed");
        return false;
    }


It seems to be like calling connect here should be accessing a method on a NULL object, but it's not. Does this method somehow act as a constructor too?
Last edited by Ben Baron on Tue Aug 18, 2015 5:45 pm, edited 1 time in total.
User avatar
By kolban
#25612 Howdy Ben,
You didn't mention what programming languages you are familiar with.

In C++ if X is a class type then:

X a;

creates an instance of X and a becomes a reference to it. In Java, a similar thing such as:

X a;

would be treated as a being a variable of type X but not an instance. One would code:

X a = new X();

in C++ the above is:

X a;

Neil
User avatar
By datltq
#25614 Hi,

A little explanation here:

Code: Select all    WiFiClient client;

This creates an instance of WifiClient and name it client. The constructor of WifiClient runs here, e.g it setup basic parameter for the wifi connection.

Code: Select all if (!client.connect(host, httpPort))

We call a method called 'connect' of the instance 'client'.
client.connect(host, httpPort) will return a value, if it is ZERO - indicate that it is failed by the one who programmed it, code in the block will run.

Bad code practice though, IMO

Dat
User avatar
By Ben Baron
#25622 Thanks for the replies guys, I didn't realize C++ had implicit initialization like that (or Java either for that matter--EDIT: never mind, just reread your post and realized you used Java as a counter example).

I code Objective-C all day so I'm used to explicitly initializing everything. Thanks for the help, I wasn't sure what to search for so figured I'd just ask here.
Last edited by Ben Baron on Tue Aug 11, 2015 9:48 am, edited 1 time in total.