This is an old revision of the document!


Structures and Classes

Structures and classes present complex data types, definable by the developer. Not all C/C++ programming environments provide support for classes (i.e., STM32 in HAL framework mode does not), but luckily, the Arduino framework supports it. Structures, conversely, are part of the C language definition and are present in almost every implementation of software frameworks for IoT microcontrollers.

Structures

In C and C++, a structure is a user-defined data type that allows you to combine different types of variables under a single name. A structure primarily groups related variables, forming a complex data type. A custom data structure (type) that can hold multiple variables, each with its own data type. These variables, called members or fields, can be of any built-in or user-defined type, including other structures. The sample named structure (equivalent to the complex type), variable declaration and use of member fields are presented below:

struct address {
  String city;
  String PO;
  String street;
  double longitude;
  double latitude;
};
...
address adr1;

Note it is also possible to declare a structure variable directly without defining a type:

struct {
  String city;
  String PO;
  String street;
  double longitude;
  double latitude;
} adr2, adr3;

Structures with type definitions are common when authoring libraries to let library users be able to declare new variables on their own, simply using a type.

Manipulating Structure's Data

Access to the fields of the structure's member variables (short: members, fields) is possible using the “.” (dot) operator.

adr1.city = "Gliwice";
adr2.city = "Oslo";
adr3.street = "Rodney";

The structure's data can be initialised member by a member or at once using the simplified syntax. Order is meaningful, and types need to fit the definition (C++ only):

adr3 = {"Liverpool", "L1 9EX", "27 Rodney", -2.973083901947872, 53.401615049766406 };

In C++, structures can also have member functions that manipulate the data (in C, they cannot). That is not so far from the Classes idea described in the following chapter. In the case of using C (or poor implementation of C++ that does not support classes nor member functions, i.e. STM32), it is common to prepare a set of data handling functions that operate on the structure referenced with a pointer. A common rule of thumb is the structure is the first argument in the function:

struct calcdata
{ 
  double x,y;
} args;
 
//Adds x and y of the "arguments" structure
double fCalcDataAdd(calcdata *arguments){
  return (arguments->x + arguments->y);
}
//Multilies x and y of the "arguments" structure
double fCalcDataMul(calcdata *arguments){
  return ((arguments->x)*(arguments->y));
}
//Sets x and y of the "arguments" structure
void fCalcDataSet(calcdata *arguments, double px, double py){
  arguments->x = px;
  arguments->y = py;
}

In the examples above, we use a “→” dereference operator to access the member fields by using the pointer to the structure rather than the structure itself.

Sample use of the functions is then:

args = {2,7};                //initialise structure x=2, y=7
fCalcDataSet(&args, 12,12);  //reinitialise structure x=12, y=12
int z = fCalcDataAdd(&args); //z equals to 24 now

Classes

Classes were introduced in C++ as an idea to extend structures that encapsulate data and methods (functions) to process this data. A method presented above in the structure context brings an overhead with a need to pass a pointer to the structure for each call. Moreover, it makes access levels tricky, i.e. when you do not want to expose some functions but rather use them for internal data processing. Thus classes can be considered as an extension of the structures.

Classes are legit only for C++ and not in regular C implementations.

Sample class definition is presented below:

class Calculator
{
  public: //you can access this part
  int x,y;
    Calculator() {  //Default constructor
      clear();
    }
    Calculator(int px, int py) { //Another constructor
      x=px; 
      y=py;
    }
    ~Calculator(){} //This is dummy destructor
    int Add(){ return x+y; }
    int Mul(){ return x*y; }
    void setX(int px){ x=px; }
    void setY(int py){ y=py; }
  private: //that part is private and you cannot access it      
    void clear(){
      x=0; y=0;
    }
};

The code above declares a new type, Calculator, with member fields (members in short) x and y and methods (functions) Calculator, Add, Mul, setX and setY. Some are marked as private: and accessible only from the code of the functions (methods) within the class; some are exposed to external users when marked as public:.
Constructors
There are “special” functions whose name is equivalent to the class name in this example above. Those are called constructors and are executed once the object of the class type is instantiated:

Calculator calc1=Calculator(2,15);

The above code instantiates an object calc1 of the class Calculator and calls the constructor explicitly Calculator(int px, int py). The other constructor, Calculator(), is the default one, and if not explicitly called by the code developer, it is automatically called when the object is instantiated.
There can be multiple constructors, and the one executed is selected based on the arguments set.
Destructor
A destructor is called automatically when an object's lifetime is to end. It allows, i.e. to release resources, disconnect open connections, and, in general, do some cleanup before the object is gone. The destructor function in the example above does nothing and is not obligatory in the code. Destructor name starts with a ~ sign (tilde) and has the same name as a class (or constructor):

~Calculator(){} //This is dummy destructor
In the embedded world, explicitly implemented destructors releasing allocated memory are rare as for the safety of the software, dynamic allocation of the memory is rather to be avoided; thus, destructors are eventually related to the network connections more than memory management.

Members
Member fields can be of any type. When marked as private, they are accessible only from the code of the constructors, destructor and methods within the class. When public, one can reference them using a “.” (dot) operator, as in the case of the structures. When using a pointer to the class instance (object) rather than an instance itself (quite common), a “→” operator works as in the case of structures.
Methods
A method can have any name other than reserved ones (i.e. for constructors and destructor). Methods marked as public are available for the object user and are referenced similarly to member fields (“.” and “→” operators). private methods are not exposed externally; their purpose is to be called from another method internally.

Class inheritance
Classes can be inherited. This mechanism enables the real power of C++, where existing models (classes) can be extended with new logic without a need to rewrite and fork code. In the example above, the Calculator class misses some features, such as i.e. subtracting. A code below defines a new type BetterCalculator that inherits from the Calculator class, using “:” operator:

 
en/iot-open/introductiontoembeddedprogramming2/cppfundamentals/structuresandclasses.1689084719.txt.gz · Last modified: 2023/07/11 11:11 (external edit)
CC Attribution-Share Alike 4.0 International
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0