CSCI 104L: Lecture 5: Abstract Data Types
CSCI 104L: Lecture 5: Abstract Data Types
We will group together all data and functions that interact with that data into a common element, or class.
This idea is called encapsulation. Here is an example class signature for a linked list of integers:
class IntLinkedList {
public :
IntLinkedList ( ) ;
I n t L i n k e d L i s t ( int n ) ;
˜ IntLinkedList ( ) ;
void prepend ( int n ) ;
void remove ( int toRemove ) ;
void p r i n t L i s t ( ) ;
void p r i n t R e v e r s e ( ) ;
private :
void p r i n t R e v e r s e H e l p e r ( Item ∗p ) ;
Item ∗ head ;
};
Here is how we will implement printReverse().
void I n t L i n k e d L i s t : : p r i n t R e v e r s e ( ) {
i f ( head != NULL) p r i n t R e v e r s e H e l p e r ( head ) ;
}
void I n t L i n k e d L i s t : : p r i n t R e v e r s e H e l p e r ( Item ∗p ) {
i f ( p−>next != NULL) p r i n t R e v e r s e H e l p e r ( p−>next ) ;
c o u t << p−>v a l u e ;
}
You can have multiple constructors. You could allow a user to start a Linked List with a single node with
value n. Both constructors can be used, one constructor does not replace the other.