Main Content

Creating, setting up and using objects in C++

Archive - Originally posted on "The Horse's Mouth" - 2010-01-16 07:12:20 - Graham Ellis

Early on this week's C++ programming course (including the C fundamentals), I wrote a new and short example that defined and used a class of objects of type "Hotel". Really, this initial example was very much shorter than any real program you would write and it used a very limited number of the facilities, but it did (and does) show the first steps towards creating objects of a type.

We created a hotel by declaring it and passing in any initial parameters to its constructor method:
  Hotel hilton(40);

We set variables within the object using the same . notation for members that we had used in the underlying C for structure members (perhaps there's a clue as to how it works internally there!):
  hilton.roomcount = 18;

We also set variables / states / used our object via methods - a much better way that setting them directly (come on the course - I'll explain why ;-) ):
  hilton.setoccu(0.75,350);

And we called back results also using object methods - named pieces of code that run on the objects:
  avoccu = hilton.getavoc();

Within the main source file for this program, we loaded in a header file that tells the compiler about the various methods which are availabe on our Hotel class, and the variables each hotel contains:
  #include "g_hotel.h";
but, significantly, that header file does NOT contain the actual code of the hotel class methods - that's written and compiled up elsewhere, perhaps by another programmer or even another company, and may be shared between a whole lot of different programs. This is one of the critically useful elements of the Object Oriented approach - the separation out of code into separate logical and separately maintained files. All the person who is making use of the classes need to know is how to call them, what they return, and what their effect is.

The complete code from which the examples above are taken is [here]. We went on to enhance the class, adding options to it ... so the header file became rather more complex than is really needed in this simple example ... and that extended header file is [here]. And the source code for the Hotel class (final version from the course) is [here].




• You'll find further (shared) use of the same class in our extended application demonstration - which used multiple classes built upon the single base class ("different types of hotel") on our site - there's quite a few files involved - so start off at the overview description [here].

• You'll find details of how to store your objects in more permanent memory on the heap rather than on the stack [here].