Cerca nel blog

Loading

22 gennaio 2008

Lesson 3: typedef, struct and class

In the previous lesson we have learned that C/C++ is able to handle several different data types (so called built-in type) in order to perform standard mathematical and logical operations. In this lesson, we will see how the programmer can define his own data type to cope with his specific needs.

Typedef: renaming an existing type

The easiest way the user has to define his own data type is via the typedef instruction. The syntax is very simple and the only thing the programmer has to do is to add the following line to his code:

typedef existing_type new_type;

At a first sight, it may seems useless to define a new type being equal to an already existing one. In other words, typedef is renaming a data type, not really creating something new, but anyway it can be very useful. Let's list some examples:
  1. Platform independent type definition. Depending on the system architecture, we may have different size for the same built-in type. This is imposing severe restrictions when the same source code is compiled and executed on different systems. In this respect, I like very much the solution adopted by the ROOT development team; they define a portable independent type (say Int_t, for instance) and they typedef it to correct type size depending on the system architecture. Have a look at the Rtypes.h include file. For this reason, I strongly recommend to always use portable types (starting with a capitol letter and ending the _t) every time the value of a variables has to be written to a file and might be read back from a computer with another architecture.
  2. Easiness of programming. Consider the case the programmer has defined a variable of the following type :
    unsigned short int *

    it is to say a pointer to a not signed short integer. If this particular type is used very often in the code, then the programmer may want to typedef it to something more compact like UShortPtr. This is even more clear when using templated container, like vectors.
Enumerations: using symbolic constants

Consider the case in your application you have a variable (month) you use to store the current month of the year. In principle you can define this variable as a character array, but then it becomes very difficult to perform operation on this variable, like incrementing by one unit to get the following month or similar thing. A very smart solution is to define a enumeration as follow:


enum month_t {
january=1, february, march, april, may, june,
july, august, september, october, november, december
} ;

Doing so, in the rest of the code you can define a variable, say currentMonth, and use it as follows:

month_t currentMonth;
currentMonth = january;
for ( currentMonth == may ) {
cout << "This is the wedding month!" << endl;
}


In other word, an enumeration is a one to one correspondence between a list of words and integer values. When should I use it? My advice is to use as often as possible in order to make the code more readable. In the case of the month of the year, the correspondence is evident to everyone, but there are several others cases in which this is not that clear. Do you want a real life example? Here you have it...


enum particle_t {
electron,
proton,
....
};

Writing particle_t myParticle = electron is by far clearer than writing particle_t myParticle = 1!!!

Structures: putting together different types

Have you ever seen one of those old library archives? Yes, I really mean those metallic cabinets containing one small piece of paper (say a record) for each book. This record is a bundle of information, some strings, as the title, the author; some integers, like the issuing year, the number of pages; some floating numbers, like the cost and so on and so forth.

Can I do the same thing in C/C++? You sure can! Just create a struct, using the following code

struct record_t {
string author;
string title;
int year;
int pages;
....
float price;
};

One can access both in writing and in reading the single element (called member) of a structure using the "." operator. For example one can set the number of pages a book in the following way:


record_t myBook;
myBook.pages = 192;

Once you have defined a struct, you can use it as any other data type. For example, it can be used as the argument of a function, you can use pointer to structures, define array...


// example of function having record_t as argument
void addBootToLibrary(record_t book);

// example of function returning an array of records
void findBookByYear(int year, record_t * bookList, int * listSize);


Classes: moving from C to C++


The concept of a class is at the base of Object Oriented Programming and we can consider it as the turning point from C to C++. A class is nothing more than the evolution of a structure in which along with data members there are also member functions (a.k.a. methods). An object, a name you'd probably heard mentioning several times, is an instantiation of a class. To make it simpler, using the variable language, the class is the type and the object is the variable itself.

Now that you know what an object is, you may wonder what Object Oriented programming means. This is a programming model that treats programming from a perspective where each component is considered an object, with its own properties and methods, replacing or complementing structured programming paradigm, where the focus was on procedures and parameters. So said, you need to rethink at your code as the interplay of several objects!

The first question you may want to ask is: Since a class can be considered a user-defined data type, how can I put a function into a type definition? Easy, you just put in the class definition as we are doing here below:


class MyClass {
public:
int getX();

private:
int _x;
};

You may find a complete example in the files attached here below:





Chiunque può lasciare commenti su questo blog, ammesso che vengano rispettate due regole fondamentali: la buona educazione e il rispetto per gli altri.

Per commentare potete utilizzare diversi modi di autenticazione, da Google a Facebook e Twitter se non volete farvi un account su Disqus che resta sempre la nostra scelta consigliata.

Potete utilizzare tag HTML <b>, <i> e <a> per mettere in grassetto, in corsivo il testo ed inserire link ipertestuali come spiegato in questo tutorial. Per aggiungere un'immagine potete trascinarla dal vostro pc sopra lo spazio commenti.

A questo indirizzo trovate indicazioni su come ricevere notifiche via email sui nuovi commenti pubblicati.

0 commenti:

Posta un commento

Chiunque può lasciare commenti su questo blog, ammesso che vengano rispettate due regole fondamentali: la buona educazione e il rispetto per gli altri.

Per commentare potete utilizzare diversi modi di autenticazione, da Google a Facebook e Twitter se non volete farvi un account su Disqus che resta sempre la nostra scelta consigliata.

Potete utilizzare tag HTML <b>, <i> e <a> per mettere in grassetto, in corsivo il testo ed inserire link ipertestuali come spiegato in questo tutorial. Per aggiungere un'immagine potete trascinarla dal vostro pc sopra lo spazio commenti.

A questo indirizzo trovate indicazioni su come ricevere notifiche via email sui nuovi commenti pubblicati.

Related Posts Plugin for WordPress, Blogger...