Chapter 6: Classes

Chapter Goals

Discovering Classes

Discovering Classes (bestval.cpp)

Interface

Interface (Syntax 6.1 : Class Definition)

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

Interface (product1.cpp)



Encapsulation

Member Functions

Member Functions (const)

Member Functions (Syntax 6.2 : Member Function Definition)

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 (Syntax 6.3 : Constructor Definition)

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.

Default Constructors (product2.cpp)

Constructors with Parameters

Accessing Data Fields

Comparing Member Functions with Nonmember Functions


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

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

Default
Example: void Employee::raiseSalary(double p)

Separate Compilation

Separate Compilation (product.h)

Separate Compilation (product.cpp)

Separate Compilation (prodtest.cpp)

Separate Compilation