Pointers to Classes


As was thoroughly explained in Chapter 8, a pointer is just a reference to an address in memory. When you create an instance of a class, it must be stored in memory as well. This means that you can also create a pointer to an object created from a class.

Hint!

Remember that a class is just a template for creating an object; you have to make an instance of the class before you can use it.

A pointer to a class is done exactly the same way a pointer to a structure is. Remember that a class is really just a structure with functions in it. This means that when you access members of a pointer to a class you use the -> operator, just as you do with pointers to structures. Also remember that, as with all pointers, you must initialize the pointer before using it. Consider the following example.

Example 10.3

Step 1: Enter the following code into your favorite text editor.

#include <iostream> using namespace std;   class myfirstclass { public:  int number;  void greeting();  }; void myfirstclass::greeting() {  for(int i = 0; i<= number;i++)  {    cout<< "Hello World \n";  } } int main ()  {      myfirstclass myfirstobject;      myfirstclass *ptrclass;      ptrclass= &myfirstobject;      ptrclass->number = 5;      ptrclass->greeting();      return 0; }

Step 2: Compile that code.

Step 3: Run the code. You should see something like what is shown in Figure 10.4.

click to expand
Figure 10.4: Pointers to classes.

All the classes you have seen in this chapter illustrate one of the four principle concepts of object orientation, and that is encapsulation. They all take the data to be stored and the functions that will manipulate that data, and put them together into a single class. This is the cornerstone of object-oriented programming. The principles of inheritance and polymorphism will be explored in more depth in the next two chapters.




C++ Programming Fundamentals
C++ Programming Fundamentals (Cyberrookies)
ISBN: 1584502371
EAN: 2147483647
Year: 2005
Pages: 197
Authors: Chuck Easttom

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net