Introduction to Classes
Classes are how c++ implements an ADT.
What is an ADT?
An important idea is encapsulation.
The data and functions are bundled.
Clients or users of the class do not have direct access to the data.
Basic Syntax
class Identifier { Access_Modifier: members Accdess_Modifier: members };
Access modifiers can be
public
: members listed with this access modifier can be accessed by anything.
private
: members listed with this access modifier can only be accessed by any instance of the class.
protected
a special case we will consider in 330.
Do not use this for now.
Members are function prototypes or variable definitions.
Access modifiers are one of the tools used to accomplish encapsulation and information hiding.
By placing a member in the private section you do not allow other entities to access it directly.
Thus they do not rely on the implementation.
But you need to place adequate access mechanisms in the public area.
Classes usually have a special function called a
constructor
This is responsible for creating an instance of the classs.
It is strange in that it does not have a return type.
But it is responsible for creating an instance of the class or "instantiating" the class.
It is named after the class.
There can be multiple of these.
Unless you have a good reason to do so, there should be one that takes no parameters.
This is called a default constructor.
There are several other types of member functions
observers
or
getters
which return values stored in the class.
transformers
or
setters
which change values stored in the class.
iterators
which we will discuss in 330.
destructors
which we will discuss later.
Let's write a really simple person class
Set the domain to be name and age.
What functions might we want to perform on this person?
Write it.
Let's think about a fraction.
What is the domain of a fraction?
What operations can you perform on a fraction?
Write it.