C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

Learn about C++ Classes and Objects

By David Bolton, About.com

4 of 9

Learn about Writing Class Methods

Best practice for objects is to make all data private and access it through functions known as accessor functions. SetPage() and GetCurrentPage() are the two functions used to access the object variable CurrentPage.

Change the class declaration to struct and recompile. It still compiles and runs correctly. Now the two variables PageCount and CurrentPage are publicly accessible. Add this line after the Book ABook(128) ; and it will compile.

ABook.PageCount =9;
If you change struct back to class and recompile, that new line will no longer compile as PageCount is now private again.

The :: Notation

After the body of Book Class declaration there are the four definitions of the member functions. Each is defined with the Book:: prefix to identify it as belonging to that class. :: is called the scope identifier. It identifies the function as being part of the class. This is obvious in the class declaration but not outside it.

If you have declared a member function in a class you must provide the body of the function in this way. If you wanted the Book class to be used by other files then you might move the declaration of book into a separate header file perhaps called book.h. Any other file could then include it with

#include "book.h"
On the next page : Learn about Inheritance

Explore C / C++ / C#

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Learn about Writing Class Methods

©2009 About.com, a part of The New York Times Company.

All rights reserved.