Home    About me    Publications    Blog    Photo gallery
Some other old good stuff

Fabio Ruini’s blog

Because Italians do it better! What the f**k? Ehm… the blogs, I mean… obviously! :-/

Archivio per Maggio, 2007

How to use classes in C++ (lesson #2)

In this second lesson, we will see how to pass a parameter from the main program to a member function. In more details, we want to be able to ask the user for the course name and then print it on the screen through displayMessage member function.


[line 01]  #include < iostream >
[line 02]  using std::cout;
[line 03]  using std::cin;
[line 04]  using std::endl;

[line 05]  #include < string >
[line 06]  using std::string;
[line 07]  using std::getline;

[line 08]  class GradeBook {
[line 09]    public:
[line 10]      void displayMessage(string courseName) {
[line 11]	  	cout << "Welcome to the grade book for\n" <<
		  	courseName << “!” << endl;
[line 12]	     }
[line 13]  };

[line 14] int main() {
[line 15]    string nameOfCourse;
[line 15]    GradeBook myGradeBook;

[line 16]    cout << “Please enter the course name:” << endl;
[line 17]    getline(cin,nameOfCourse);

[line 18]    myGradeBook.displayMessage(nameOfCourse);
[line 19]    return 0;
[line 20] }

The procedure is very easy.

In the main function, we first declare a string variable called nameOfCourse (line 15) and then we prompt the user with a “Please enter the course name” question (line 16). The answer will be stored in the just defined variable (line 17).

Then we call the displayMessage function (line 18), passing to it nameOfCourse. In fact, the member function, as defined at line 10, is now able to receive an input parameter (a string). The value stored in this parameter, called courseName inside the function, will be displayed on the user’s screen, prefixed by the string: “Welcome to the grade book for ” (line 11).

iTunes U

Nel giorno in cui tutti i riflettori sono puntati sulla “uscita” di iTunes Plus, è per forza di cose finito in secondo piano un altro servizio offerto contestualmente da Apple. E non mi sto riferendo alla nuova Apple TV finalmente con un hard disk di dimensioni decenti (160 GB) o all’accordo con YouTube per trasmettere sul gingillino con la mela sopra i filmati reperibili sul portale di video-sharing. Parlo invece di iTunes U.

Podcast Berkeley

Centinaia di ore di lezioni, conferenze, seminari e quant’altro, registrati presso alcune delle più importanti università/centri di formazione USA (tanto per citarne qualcuna: Berkeley, Stanford, MIT). Qualità garantita ed il tutto assolutamente gratuito. Scaricabile da iTunes e trasferibile sul proprio iPod. Bello, bello, bello. Non c’è altro da aggiungere!

Il mio curriculum diventa internazionale

Globe

Ci avrò speso sopra due ore. Ma prima o poi andava fatta. Intendo la traduzione/conversione del mio curriculum in inglese. E questo è il risultato che, bisogna ammetterlo, suona molto più professionale rispetto a prima…

Metti una mattinata al mare

Dopo uno dei peggiori weekend festivi degli ultimi anni (weekend lungo, perchè qui oggi è ancora Bank Holiday), stamattina ho approfittato del sole per andare finalmente a visitarmi la zona turistica di Plymouth. Alias, il Barbican e lo Hoe. Sì, il leggendario faro sotto al quale, leggenda vuole, sir Francis Drake stesse giocando a bocce quando una vedetta lo informò sul fatto che la flotta spagnola, altamente incazzata, era nei paraggi. Il buon Drake, sempre secondo la tradizione, finì in tutta tranquillità la sua partita di bowl, salì in barca e devastò gli spagnoli.

Beh, davvero una bella sorpresa questi posti. Me ne avevano parlato bene in molti ed ero infatti piuttosto incuriosito. Ma lo spettacolo è andato ben al di là delle mie migliori aspettative. Unico problema, un vento che letteralmente portava via. Alcune foto le ho dovute rifare n volte perchè davvero non riuscivo a tenere la macchina fotografica ferma. Qualche bello scatto, però, è venuto fuori lo stesso:

Plymouth Hoe

Cannon

Plymouth - first trans-oceanic flight

The Sea

Plymouth Gin Distillery

Il resto delle foto, al solito, le trovate nella sezione Plymouth della PhotoGallery.

Il paradiso dei fumatori…

… non solo di sigarette rollate, mi sa! :-)

Stavo vagando su Internet alla ricerca del modo di risparmiare qualche soldo nell’acquistare cartine e filtri per le mie sigarette hand-rolled. Alle quali, per inciso, ho cominciato a dedicarmi a partire dallo scorso martedì, appena finita la stecca di Marlboro portata dall’Italia. Per ora sta andando bene. Inizio a prenderci la mano nel rollare, ottime le Rizla verdi che sto usando e pure il tabacco (Golden Virginia) non è per niente male. L’unico problema sono i filtrini, che mi piace usare, ma che qui non riesco a trovare della dimensione che voglio (King Size, ma lunghi solo 8mm… il pacchetto preso in Italia è agli sgoccioli, anche se in settimana dovrebbero arrivare rifornimenti dalla madre patria).

Va beh, fatto sta che su eBay sono riuscito a fare scorta di cartine a bassissimo prezzo (40 pacchettini di cartine per 8 sterline comprensive di spedizione), ma non a trovare i filtri.

In compenso ho trovato questo negozio:

Roll-ups.co.uk – Make Your Own Cigarettes

Tra le autentiche chicche ivi presenti:

  • un salvadanaio dedicato a chi vuole smettere di fumare:

    Saving tin

  • mutandine (per lei) fatte di confetti (purtroppo c’è anche la versione perizomata maschile):

    Candy String

  • contenitori “sicuri” per nascondere il fumo:

    Safe can

E tante altre cosine interessanti. Consiglio assolutamente una visita!

How to use classes in C++ (lesson #1)

Visto e considerato che a scrivere in inglese, per quanto i risultati siano ancora tendenti all’orrido, ci sto prendendo gusto. Visto e considerato che mi sembra di essere tornato indietro di qualche mese, a quando ero chino sui libri a studiare per qualche esame. Visto e considerato che la tecnica migliore per studiare, per il sottoscritto, è sempre stata quella di leggere e scrivere riassunti (spesso più lunghi del libro originale, ma la mia incapacità di sintesi è un’altra storia). Beh, ecco che ora provo a farlo in inglese. Con un mini-tutorial su come utilizzare le classi in C++. D’accordo, non uno degli argomenti più stimolanti del pianeta, ma da qualche parte si doveva pur partire. E siccome sto studiando proprio questa roba…

Lesson for a soldier

We begin with an example. Imagine you have to develop a class, called “GradeBook” dedicated to manage a grade book that an instructor can use to maintain student test scores. Take a look to the code posted below:

[line 1]  #include < iostream >
[line 2]  using std::cout;
[line 3]  using std::endl;

[line 4]  class GradeBook {
[line 5]     public:
[line 6]        void displayMessage() {
[line 7]	   cout << "Welcome to the Grade Book!" << endl;
[line 8]	}
[line 9]  };

[line 10] int main() {
[line 11]    GradeBook myGradeBook;
[line 12]    myGradeBook.displayMessage();
[line 13]    return 0;
[line 14] }

This is a complete and working C++ program. The first three lines are dedicated to preliminary operations: to include the iostream library and to provide the programmer with the possibility of call cout and endl functions, from the STD library, without the need of use the complete std::function_name statement. Lines 2 and 3 provide an advantage (in terms of memory occupation) with respect to the more common using namespace std instruction, which include all the functions contained in the C++ Standard Template Library.

The GradeBook class definition starts at line 4, with a very simple syntax:

	class ClassName {

At line 5 we can see a public: statement, better known as an “access-specifier label”. Its role is to signal that the following member functions and/or data members, still belonging to this class, are “available to the public” (i.e., they could be accessed everywhere along the program – not only by the member functions belonging to the class). All the member functions and data members defined after the public: statement – until the compiler will find the right bracket and the semicolon that end the class definition or until a different access-specifier label (e.g., private:) is encountered – belong to the defining class.

The instruction presented at line 6 starts to define a member function for the GradeBook class, called displayMessage. This function doesn’t returns any value (its return type has been set as void) to its calling function, as well as it doesn’t need any input parameters (parenthesis following its name are empty).

Again, the syntax is simple:

	return_type functionName(parameters_list) {

Then, at line 7, we have the instruction (yes, just one) composing the body of displayMessage member function. This instruction simply prints a welcome message on the screen.

At line 8 the member function definition ends, as well as at line 9 the right bracket and the semicolon character signal the end of the class definition.

Now it’s time to look at the main function. First of all (line 11), we create a GradeBook object (an instance of GradeBook class, in class-related lexicon) called myGradeBook, using the following syntax:

	ClassName instanceName;

Then we call the displayMessage function (line 12), with refer to the just created object. The C++ syntax needs the name of the object, followed by a dot (.) and then by the name of member function to be called (including the eventual list of parameters).

	instanceName.functionName(parameters_list);

Lines 13 and 14, finally, close the program.

Congratulation. You just created your first class.

[The example provided has been entirely copied from:
H.M. Deitel, P.J. Deitel - "C++ How to Program"]

Sainsbury’s

Una delle domande più assillanti a cui sono costretto a rispondere da quando sono qui a Plymouth è una di quelle più classiche: “Ma è molto cara la vita lì?!?“. Premesso che ancora non sono riuscito a capirlo io, lascio a voi il compito di giudicare. Questa la mia spesa settimanale, fatta da Sainsbury’s (che, off course, dovrebbe essere uno dei supermercati più economici della zona) e portata a casa giusto una decina di minuti fa:

Sainsbury’s bag

Natura morta: la mia bellissima borsina per la spesa da tipica massaia inglese…

  • 1 pacco di spaghetti;
  • 1 pacco di fusilli;
  • 1 pacco di penne rigate (tutti e tre da 500 grammi e firmati De Cecco);
  • 1 sugo Knorr formato grande;
  • 8 banane;
  • 6 uova;
  • 4 limoni;
  • 1 sacchetto di insalata;;
  • 2 pacchettini di “cubetti di pancetta” (scritto esattamente così sulla confezione) (sì, oggi ci scappano finalmente i miei adorati spaghetti alla carbonara);
  • 1 pacco di caffè Lavazza Crema e Gusto;
  • 1 paccone di bustine per il the;
  • 1 pacco di pane da toast;
  • 1 mini-baguette;
  • 1 busta di prosciutto di Parma;
  • 2 pacchettini di bacon (non mi ricordo il peso, ma di solito con un pacchetto ci mangio due volte, se faccio ovviamente un primo+secondo);
  • 1 pacchetto di “Garlic Chicken Kiev”, alias due pezzi di pollo ripieni di questa salsa che non sono ancora riuscito a decifrare, ma che mettono sempre dentro anche al pane pre-cotto;
  • 2 “oven-food” (mio nome tecnico, che non credo abbia corrispondenza nella realtà… è per distinguerli dal microwave-food e dal can-food): chiken & fries, breaded mushrooms;
  • 1 rotolo di carta da forno;
  • 1 spazzolino da denti (con “Pulsar”, non vedo l’ora di provarlo!)

Totale: 32.02 pounds. A grandi linee 45 euro. Mi sembra che siamo assolutamente in linea con l’Italia, o almeno con una delle più care parti dell’Italia, che guarda caso è quella dove abito…

Basic Object Technology Concepts

Fase di studio. Devo colmare le mie lacune relative alla programmazione ad oggetti, ai puntatori (quanti ricordi… è dalla quinta superiore che non riesco a farmeli entrare in testa) e quindi darmi pesantemente alle Qt. In realtà, ho già letto i primi due capitolo del manuale sulle Qt di cui parlavo qualche post fa e per ora è tutto abbastanza chiaro. L’esempio dei colliding mice, inoltre, potrei teoricamente già iniziare a modificarlo per adattarlo alle mie esigenze. Non sarebbe una cosa così impossibile, tutt’altro, ma visto che il tempo c’è voglio provare a fare le cose con calma.

Approfitto della situazione per citare, dal possente manuale “C++ How to Program, 5/E” di H.M. e P.J. Deitel, una splendida introduzione alla programmazione orientata agli oggetti:

Isometric shapes

We begin our introduction to object orientation with some key terminology. Everywhere you look in the real world you see objects – people, animals, plants, cars, buildings, computers and so on. Humans think in terms of objects. Telephones, houses, traffic lights, microwave ovens and water coolers are just a few more objects we see around us every day.

We sometimes divide objects into two categories: animate and inanimate. Animate objects are “alive” in some sense – they move around and do things. Inanimate objects, on the other hand, do not move on their own. Objects of coth types, however, have some things in common. Thay all have attributes (e.g., size, shape, color and weight), and they all exhibit behaviors (e.g., a ball rolls, bounces, inflates and deflates; a baby cries, sleeps, crawls, walks and blinks; a car accelerates, brakes and turns; a towel absorbs water). We will study the kinds of attributes and behaviors that software objects have.

Humans learn about existing objects by studying their attributes and observing their behaviors. Different objects can have similar attributes and can exhibit similar behaviors. Comparisons can be made, for example, between babies and adults and between humans and chimpanzees.

Object-oriented design (OOD) models software in terms similar to those that people use to describe real-world objects. It takes advantage of class relationships, where objects of a certain class, such as a class of vehicles, have the same characteristics – cars, trucks, little red wagons and roller skates have much in common. OOD takes advantage of inheritance relationships, where new classes of objects are derived by absorbing characteristics of existing classes and adding unique characteristics of their own. An object of class “convertible” certainly has the caracteristics of the more general class “automobile”, but more specifically, the roof goes up and down.

Object-oriented design provides a natural and intuitive way to view the sofware design process – namely, modeling objects by their attributes, behaviors and interrelationships just as we describe real-world objects. OOD also models communication between objects. Just as people send messages to one another (e.g., a sergeant commands a soldier to stand at attention), objects also communicates via messages. A bank account object may receive a message to decrease its balance by a certain amount because the customer has withdrawn that amount of money.

OOD encapsulates (i.e., wraps) attributes and operations (behaviors) into object – an object’s attributes and operations are intimately tied together. Objects have the property of information hiding. This means that objects may know how to communicate with one another across well-defined interfaces, but normally they are not allowed to know how other objects are implemented – implementation details are hidden within the object themselves. We can drive a car effectively, for instance, without knowing the details of how engines, transmissions, brakes and exhaust systems works internally – as long as we know how to use the accelerator pedal, the brake pedal, the steering wheel and so on. Information hiding, as we will see, is crucial to good software engineering.

Languages like C++ are object oriented. Programming in such a language is called object-oriented programming (OOP), and it allows computer programmers to implement an object-oriented design as a working software system. Languages like C, on the other hand, are procedural, so programming tends to be action oriented. In C, the unit of programming is the function. In C++, the unit of programming is the class from which objects are eventually instantiated (an OOP term for “created”). C++ classes contain functions that implement operations and data that implements attributes.

C programmers concentrate on writing functions. Programmers group actions that perform some common task into functions, and group functions to form programs. Data is certainly important in C, but the view is that data exists primarily in support of the actions that functions perform. The verbs in a system specification help the C programmer determine the set of functions that will work together to implement the system.

(H.M. Deitel, P.J. Deitel, “C++ How to Program, 5/E“)

Varie ed eventuali pescate in rete

Post “di servizio”, per segnalare alcune cose piuttosto interessanti pescate in rete, una delle quali su segnalazione di Davide:

  • SlideShare.net: il concetto di fondo è lo stesso di YouTube. Con SlideShare, però, non si mettono in condivisione dei filmati, ma bensì delle presentazioni. Ho provato a caricare la presentazione che avevo usato per la tesi, a mo di prova, e devo ammettere che il risultato, come si può vedere qui sotto, non è per niente male:

  • aNobii: social sharing per i libri. Ottimo il sistema di inserimento/ricerca dei volumi, ma ancora pochissime le funzionalità che ne possono fare uno strumento davvero interessante. D’accordo, diamogli tempo. Nel frattempo, questo pomeriggio ho speso una bella oretta del mio tempo per inserire i libri che sono riuscito a ripescare dagli abissi della mia memoria. Ne mancano ancora un sacco, mi sa, soprattutto di storia, ma prima o poi mi verranno in mente tutti. Questo, allo stato attuale, il mio bookshelf. E, nella sidebar di sinistra del blog, trovate (troverete) (forse) anche qualche estratto random, con tanto di copertina (ove aNobii è stato capace di rintracciarla). Ah, se siete davvero malati, potete pure iscrivervi alla mia biblioteca via RSS. Ma davvero dovreste avere problemi seri…
  • infine una bella presentazione di Barry Trimmer sul tema dei Soft-bodied robots. Premetto che è lunghina, ma ne vale la pena.

UK TV Licence

Nota positiva:

New TV

Esatto. Da oggi, nella mia cameretta, c’è una tv semi-nuova. E per quanto io odi dal profondo del cuore questo tipo di scatolette con le antenne, ci sono due ottimi motivi per piantarsela in camera: l’inglese (con il quale oggi vado però splendidamente d’accordo, in modo diametralmente opposto rispetto a ieri) e la partita di stasera.

Nota negativa (è un link):

TV Licence

Esatto. 130 sterline all’anno di TV licence, alias canone. La prossima volta vado a vedermela allo stadio la finale di Champions…

Update, 10:14pm – Sì, bell’esordio per la TV. Bravo Milan. Come ha detto il commentatore, chiudendo il collegamento: “Due anni fa il Liverpool ha giocato bene sei minuti e vinto la Champions. Questa volta il Liverpool ha giocato bene 90 minuti e la coppa l’ha portata a casa il Milan. This is football…”. Già… Piuttosto, una domanda a chi si è seguito la partita dall’Italia. Qui hanno fatto ascoltare, nella sigla finale, il “commento” di Piccinini durante le azioni che hanno portato ai due gol del Milan. Ma di che cosa si era stra-fatto? E soprattutto, ma che cazzo ci faceva Berlusconi di fianco a Platini mentre consegnavano le medaglie?

Pagina Successiva »