Structs and Classes

A struct is a class in which all data is public. To access its members, we use the dot notation.

	struct DATE
	        int month, day, year;
	} ;

        // Declaration
	DATE firstDay;

        // Accessing
	firstDay.month = 1;
	cout <<;
	if (firstDay.year == 1999)
Technically, a class is a user defined data type. It is desirable that these types behave, as much as possible, like built-in types.

Classes in C++ have two types of members: data and methods. The very simplest classes may not require any methods at all and might be better expressed as a struct.

Class Declarations
A class header contains the declarations of all data members and the prototypes of all methods. Members may be tagged as either public or private. Public members of a class are accessible to all outside modules. Private members are accessible only to other members of the class.

A well constructed class will have certain features:

These are considered necessary for any well-defined class. The class should also have some methods (functions and operations on the object).

A class may include one or more constructor functions. A class constructor is invoked whenever an instance of that class is declared. If a class contains multiple constructors, then the constructor used is determined by the number and type of parameters provided. Constructors always have the same name as the class that contains them and never have a return type.

A class may also contain a single destructor. The destructor is invoked when the scope of an object is over. This occurs when the function where the object was declared ends. A destructor has the same name as the class that contains it, prefaced with a tilde (~).

C++ allows the programmer to define what should happen when a user-defined object is used in conjunction with a built-in operator (e.g., + or %). Thus, for example, the + operator can be overloaded so that it can be used to add fractions, even though fraction addition is not built into the language. An overloaded operator is defined much like a function.

Refer to the code below for questions 1 - 4.

	struct CHAPTER
	     apstring title;
	     int nPages;
	     int firstPageNo;
	struct BOOK
	     apstring title;
	     int numChapters;
	     int nPages;
	} ;
	BOOK book;
  1. Draw a diagram, showing what a BOOK object looks like.

  2. Write the expression for the number of chapters in book.

  3. Write an expression for the title of the third chapter in book.

  4. Write the expressions for the number of pages and the first page number in the last chapter in book.

  5. Write a function below the following header that prints the table of contents (the title and first page number of each chapter in the book).

	void TOC (const BOOK &book)

Continue to:  Unit 4  / Prev  / Next