Structs, what are those?


 
Download Code Example Here


You might not ever come across a struct, but you might still want to know what they are.
They're basically the predecessor to the 'class', and before object oriented programming became a thing people used to use them a lot. They're still around, and in C++ a struct and a class are very similar except a struct's members are public by default.


The basic form of a struct looks like this:

struct user{

  String userName;

  String superSecretPassword;

  int someNumber;

   

  };


In this example, you've defined a struct called 'userr' that has the fields userName, superSecretPassword, and someNumber in it. 

This struct is a type - similar to an int, or a string you can declare a variable to be of type customer  like this:

user currentUser;

Now, you can access the fields you created in your struct like this:

struct user{

  String userName;

  String superSecretPassword;

  int someNumber;

  };


  user currentUser;


void setup() {

  // put your setup code here, to run once:

  currentUser.userName = "Bob";

  currentUser.superSecretPassword = "NobodyCanGuessThis";

  currentUser.someNumber = 22;

  Serial.begin(9600);

  Serial.println(currentUser.userName);

  Serial.println(currentUser.superSecretPassword);

  Serial.println(currentUser.someNumber);

}


Of course, you can also declare fields to be private with the private: key word like this:

struct user{

  String userName;

  int someNumber;

  private:

  String superSecretPassword;

  

  };



Now, if you've done this, you can only access the superSecretPassword field from code within the struct.  so 

 currentUser.superSecretPassword = "NobodyCanGuessThis";

will be an error.

So now you'll have to change your struct to add some functions that access the private fields in order to to anything with them, then invoke those functions to do work. 
Here's a sample:


struct user{

  String userName;

  int someNumber;

  bool matches(String password){

    return password==superSecretPassword;

  }

  void setPassword(String password){

    superSecretPassword = password;

  }

  private:

  String superSecretPassword;

  

  };


  user currentUser;


void setup() {

  // put your setup code here, to run once:

  currentUser.userName = "Bob";

  currentUser.setPassword("monkey123");

  currentUser.someNumber = 22;

  Serial.begin(9600);

  Serial.println(currentUser.userName);

  Serial.println(currentUser.matches("monkey124")); // returns 0 (false)

  Serial.println(currentUser.matches("monkey123")); // returns 1 (true)

  Serial.println(currentUser.someNumber);

}


Happy Coding!

~Tom








Comments

Popular posts from this blog

Using GIT with Arduino

Programming Arduino with Regular Expressions

Organize your Arduino code with header and class files