Sie sind auf Seite 1von 5

Dr Jan Pajak

Classes and Data Abstraction


(OO C++, topic 6)

#1.Textbook:
[3] Deitel & Deitel, “C++ How to program” (3rd edition, Prentice Hall, 2001, ISBN 0-13-089571-7,
pb, pp. 1168), chapter 6, pages 389-451.

#2. Objective ([3] p. 389): To be able to create C++ classes, to understand how to create, use,
and destroy class objects, and to access to object data members.

#3. Introduction ([3] pp. 390-391):


-In C++ programmers create their own user-defined types, called classes.
-Each class contains data (called “data members”) as well as functions that manipulate that data
(celled member functions).
-An instance of a class is called an object (this is like an instance of an int is called a variable).
-Classes are natural evolution of the C notion of struct.

#4. Structures in C++ ([3] pp. 391- 395):


Structures are aggregate data types built using elements of other types, including other
structs. Consider the structure definition of:
struct Calendar //keyword = struct, identifier = Calendar (used later to declare variables of the
struct type
{
int day; //structure member 1 – with a name unique for that structure, values 0-31
int month; //struct member 2 – cannot be instance of Calendar, value 0-12
int year; //0-3333
}; //each structure definition must end with ;

Properties of structures:
-They do not reserve any space in memory,
-They are used to declare data types.

Declaring structures’ variables:


Calendar CalendarObject; //declares CalendarObject variable;
Calendar CalendarArray[10]; //declares Calendar Array object;
Calendar *CalendarPointer; //declares CalendarPointer to a Calendar object;
Calendar &CalendarRef; //declares &CalendarRef as a reference to a Calendar object.

Accessing Members of structures:


We use the member access operator – the dot operator(.), and the arrow operator (->).
The dot operator accesses a structure or a class member via the variable name for the
object. For example, this prints member day of structure CalendarObject:
cout << CalendarObject.day;
The arrow operator (->) accesses a structure member or class member via a pointer to the
object. For example:
CalendarPointer = &CalendarObject
(this assigns address of structure CalendarObject to CalendarPointer)

1
To write member day of the structure CalendarObject referenced by CalendarPointer we need to
write:
cout << CalendarPointer->day;

Note that:
CalendarPointer->day is equivalent to (*CalendarPointer).day.

#5. Implementing Calendar data type with a class ([3] pp. 395-399):
Classes enable programmer to model objects that have:
-attributes (represented as data members), and
-behaviours or operations (represented as member functions, or methods).

Class definition ([3] p. 396):


It begins with the keyword class, and is followed by a block, e.g.:

class Calendar
{ //this begins the body of class definition – this body finishes with }
public: //this is a member access specifier public (accessible to all) – notice (:)
Calendar(); //this is a constructor for the class Calendar (it always has the name of its
class)
void setCalendar (int, int, int); //set day, month, year
void printMilitary(); //print military Calendar format
void printStandard(); //print standard Calendar format
~Calendar();//this is a destructor of that class (see [3] p. 419)
private: //member access specifier private (accessible only to member functions of this class) – notice (:)
int day;
int month;
int year;
}; // this ends body of the class – notice (;)

Examples ([3] p. 397): An example of a complete driver program that implements Calendar data
type with a class, including results produced by such a program, is provided in Fig. 6.3 of [3] –
see pages 397 – 399.

#6. Class scope and accessing class members ([3] pp. 402-403):
By the term “class scope” we understand a class’ data members (i.e. variables defined in
the class definition) and member functions (i.e. functions declared in the class definition). An
alternative to “class scope” is “file scope”, which includes all non-member functions. (Note that
this idea is a bit similar to “global variables” and “local variables”).
Within a class‘ scope all class members are immediately accessible by all member
functions of that class and can be referenced by name. For example see Fig. 6.4 from p. 403 of
[3]:
class Count
{
public:
int x; //declares an integer data member “x”
void print() {cout <<x <<endl;} //declares a member function print() which accesses x
};
Outside a class’ scope class members are referenced through one of the handles on an
object, namely:

2
-An object name, for example (see Fig. 6.4 from p. 403 of [3]):
int main()
{
Count counter, //create counter object of the Count class
*counterPtr = &counter, //pointer to counter
&counterRef = counter //reference to counter.
cout <<”assign 7 to x and print using the object’s name: “;
counter.x = 7;//assign 7 to data member x
counter.print(); //printing through the reference to the name of member function print()

-A reference to an object, for example (see [3] page 403, Fig. 6.4):
cout <<”Assign 8 to x and priont using a reference: “;
counterRef.x=8;//assigns 8 to data member x
counterRef.print();//calls member function print()

-A pointer to an object, for example (see [3] p. 403, Fig. 6.4):


cout <<”Assign 10 to x and print using a pointer: “;
counterPtr->x=10; // assign 10 to data member x
counterPtr->print(); //call member function print()
return 0;
}
Notice that the operators used to access class members are identical to operators used to access
structure members. The dot member selection operator (.) is combined with an object’s name or
with a reference to an object to access the object’s members. The arrow member selection
operator (->) is combined with a pointer to an object to access that object’s members.
Notice that on different occasion classes may also use “scope resolution operator” (::). It
allows e.g. to access hidden global variables (see [3] chapter 3).

#7. Initialising class objects: constructors (see [3] pp. 413-417):


When a class object is created, its members can be initialised by the class’ constructor
function. A constructor is a class member function with the same name as the class. The
programmer provides the constructor, which is then invoked automatically each time an object of
that class is created (initiated). Data members must either be initialised in a constructor of the
class, or their values may be set later after the class is created. However, it is a good
programming and software engineering practice to ensure that an object is fully initialised before
the client code invokes the object’s member functions.
Constructors can contain default arguments. Example from Figure 6.8 on page 415 of [3]
redefines the Calendar() constructor function to include default arguments of zero for each
variable, i.e.:
class Calendar
{
public:
Calendar (int = 0, int = 0, int = 0);
void setCalendar(int, int, int);
void printMilitary();
void printStandard();
private:
int day;
int month;
int year;

3
};

#8. Using destructors (see [3] pp. 418-421):


A destructor is a special member function of a class. The name of the destructor for a
class is the tilde (~) character followed by the class name, e.g. for the Calendar class it would
read:
~Calendar();
The declaration of a destructor usually is placed at the end of public part of class’ body. An
example is on pages 420 and 421 of [3].

A destructor receives no parameters and returns no value. A class may have only one destructor.

#9. Example of a driver program that tests your skills on classes and objects.
For an example of such driver program, let us consider a program that creates a class
called cube. It is to read the side dimension of that cube, and then to calculate and to display the
volume and the surface area of that cube. Here is the code of that program in C++ (console
notation):

//---------------------------------------------------------------------------
//A driver program for testing a class named "square_bar"
//It inputs the side_dimension and height of a square_bar,
//while outputs the volume and surface area of that square_bar
//Prepared by Dr Jan Pajak, at ..., on ....
//---------------------------------------------------------------------------
#include <iostream.h>
#include <conio.h>
#include <cstdlib>
//Class definition
class square_bar
{
public:
square_bar(); //class constructor
void get_data(float, float); //member function for data input
void calculate_volume(); //member function for volume calculation
void calculate_surface(); //member function for surface calculation
void display_results(); //member function for displaying results
~square_bar(); //class destructor
private:
float side_dimension;//declares a side_dimension of a square_bar (input)
float height; //declares a height of the square_bar (input)
float volume; //declares a volume of the square_bar (output)
float surface; //declares a surface area of a square_bar (output)
};
//---------------------------------------------------------------------------
square_bar::square_bar() //the constructor - it sets default values
{
side_dimension = height = volume = surface = 0.0;
}
void square_bar::get_data(float a, float h) //this member function inputs data

4
{
side_dimension = a;
height = h;
}
void square_bar::calculate_volume() //this member function calculates the volume
{
volume = (side_dimension * side_dimension) * height;
}
void square_bar::calculate_surface() //it calculates the surface
{
surface = (4.0 * side_dimension * height) +
(2.0 * side_dimension * side_dimension);
}
void square_bar::display_results() //it displays results
{
cout <<"\nThe volume of the square_bar is: "<<volume<<endl;
cout <<"\nThe surface area of the square_bar is: "<<surface<<endl;
}
square_bar::~square_bar() //the destructor - it destroys the object
{
cout <<"\nThe bar object was destroyed!" <<endl;
}
//Functions headers
void display_end(void); //this declares that there is a "file scope" function
//Follows a driver program that tests the square_bar class
int main()
{
square_bar b; //creates an object for this class
float a, h = 0.0; //declares and initiates variables to be used
cout <<"Enter a side_dimension of a square_bar : ";
cin >>a;
cout <<"Enter the height of the same square_bar: ";
cin >>h;
b.get_data(a, h); //inputs values for variables
b.calculate_volume(); //calculates volume
b.calculate_surface(); //calculates surface
b.display_results(); //displays results
b.~square_bar(); //destroys the square_bar object
display_end(); //runs the "file scope" function to report end
return 0; //this is needed as main() is int not void
}
void display_end(void) //defines the "file scope" function
{
cout <<"\nThe correct end of run of that program!\n";
system("pause");
}
//---------------------------------------------------------------------------

Das könnte Ihnen auch gefallen