Chapter 6: Classes

Chapter Goals

Discovering Classes

Discovering Classes (bestval.cpp)


Interface

Syntax 6.1: Class Definitions

class Class_name {
public:
constructor declarations
member function declarations
private:
data fields
};
Example:
class Point {
public:
Point (double xval, double yval);
void move(double dx, double dy);
double get_x() const;
double get_y() const;
private:
double x;
double y;
};
Purpose: Define the interface and data fields of a class.

Interface (product1.cpp)



Encapsulation


Member Functions

Syntax 6.2: Member Function Definition

return_type Class_name::function_name(parameter1, ..., parametern) [const]opt
{
statements
}
Example:
void Point::move(double dx, double dy)
{ x = x + dx; y = y + dy;
}
double Point::get_x() const
{ return x;
}
Purpose: Supply the implementation of a member function.

Default Constructors

Default Constructors (product2.cpp)


Constructors with Parameters

Syntax 6.3: Constructor Definition

Class_name::Class_name(parameter1, ..., parametern)
{ statements
}
Example:
Point::Point(double xval, double yval)
{ x = xval; y = yval;
}
Purpose: Supply the implementation of a constructor.

Accessing Data Fields


Comparing Member Functions with Nonmember Functions


Explicit Parameter Implicit Parameter
Value Parameter
(not changed)
Default
Example:
void print(Employee);
print(harry);
Use const
Example:
void Employee::print()const;
harry.print();
Reference Parameter
(can be changed)

Use &
Example:
void raiseSalary(Employee& e, double p);
raiseSalary(harry, 10);

Default
Example:
void Employee::raiseSalary(double p);
harry.
raiseSalary(10);


Separate Compilation

Separate Compilation (product.h)

Separate Compilation (product.cpp)

Separate Compilation (prodtest.cpp)