Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

C++ Interface vs.

Implementation
CPSC 1070, Donald House, Clemson University

10/25/19
Some Nomenclature
• Interface is that part of a class that is accessible to the
outside, namely what is in the public section of the class.

• Implementation is the set of private data structures and the


code for that implements the methods that act on the data.

• The conceptual power of this separation is that code


outside of a class does not need to know anything about
how data is structured in the class, only how to call the
class’ methods.

• This means that data structures and code for a class can
be modified without affecting code making use of the class
Example Interface
Array based stack List based stack

Although the internal structure ofstruct


the two Stack
Entry{
int value;
classes is the same, the external interface is identical.
Entry *next;
So, a program needing a Stack could
}; use either.
class Stack{
private: class Stack{
int values[MAXSTACK]; private:
int top; Entry *top;

public: public:
Stack(); Stack();
~Stack(); ~Stack();

void clear(); void clear();

bool empty() const; bool empty() const;

void push(int newvalue); void push(int newvalue);

int pop(); int pop();


}; };
Example Implementations
Array based stack List based stack

Although the interfaces of the two classes


struct Entry{ are
identical, the implementation is quite different. A user
of the class would not see any difference.
// push a new value onto the stack
// push a new value onto the stack void Stack::push(int newvalue){
void Stack::push(int newvalue){ Entry *newentry = new Entry;
if(top < MAXSTACK) newentry->value = newvalue;
values[top++] = newvalue; newentry->next = top;
else{ top = newentry;
cerr << "stack overflow" << endl; }
exit(1); // return a value from the top of the stack
} int Stack::pop(){
} Entry *topentry;
int topvalue;

// return a value from the top of the stack if(!empty()){


topentry = top;
int Stack::pop(){ topvalue = topentry->value;
if(!empty())
top = topentry->next;
return values[--top]; delete topentry;
else{
return topvalue;
cerr << "stack underflow" << endl; }
exit(2); else{
} cerr << "stack underflow" << endl;
exit(2);
} }
}
Example Usage
Array based stack List based stack
Because the interfaces are identical, this code will run
without any modifications using either Stack
implementation.
#include <iostream>
#include "Stack.h"
using namespace std;

int main(){
Stack mystack;
int num;

cin >> num;


while(!cin.eof()){
mystack.push(num);
cin >> num;
}

while(!mystack.empty()){
num = mystack.pop();
cout << num << ' ';
}
cout << endl;

return 0;
}
Example Stack and
Queue Interfaces and
Implementations
Download from the schedule page

You might also like