COMP151 l02 Classes
COMP151 l02 Classes
C++:
Data Abstraction & Classes
A Brief History of C++
• Data Abstraction
• Questions:
– What is a ‘‘car''?
– What is a ‘‘stack''?
1 data
2
3
size
top
.
.
.
.
Example: Implement a Stack with a Linked List
top
-999
top
(latest item)
-999 1 2
Information Hiding
// basic operations;
void push(int x); // add another datum
int pop(); // get the most recent datum
// status operations;
int num_elements() const;
bool empty() const;
bool full() const; member functions
}
(public interface)
Example: stack_ll.h
public:
Stack(int N); // a constructor
~Stack(); // destructor
// basic operations;
void push(int x); // add another datum
int pop(); // get the most recent datum
//status operations;
int num_elements() const;
bool empty() const;
member functions
bool full() const;
} (public interface)
Class Name: Name Equivalence
• Data members can be any basic type, or any user-defined types that
have already been “seen” (defined).
class X {
public:
int a = 1; // ERROR: can’t initialize member variables this way
};
void main()
{
X x;
cout << '' x.a = '' << x.a << endl;
}
class Stack
{ …
void push(int x) { *top = x; ++top; }
int pop() { - - top; return (*top); }
};
Member Functions of a Class
class Stack
{ …
void push(int x);
int pop();
};
void Stack::push(int x) { *top = x; ++top; }
int Stack::pop() { - - top; return (*top); }
int main()
{
Stack x;
cout << x.size; // OK: size is public
x.push(2); // OK: push() is public
cout << x.top->data; // ERROR: cannot access top
}
How Are Objects Implemented?
• Each class object gets its own
copy of the class data size
members. stack x top
• But all objects of the same data
class share one single copy of size
the member functions. stack y top
data
.
int main() .
.
{
Stack x, y; push()
x.push(1); pop()
y.push(2);
y.pop();
}