Home > Articles > Programming > C/C++

A Tour of C++

This chapter is from the book

2.5 Data Abstraction

Modularity is a fundamental aspect of all successful large programs. However, modules in the form described previously are not sufficient to express complex systems cleanly. Here, I first present a way of using modules to provide a form of user-defined types and then show how to overcome some problems with that approach by defining user-defined types directly.

2.5.1 Modules Defining Types

Programming with modules leads to the centralization of all data of a type under the control of a type manager module. For example, if we wanted many stacks—rather than the single one provided by the Stack module above—we could define a stack manager with an interface like this:

namespace Stack {
  struct Rep;       // definition of stack layout is elsewhere
  typedef Rep& stack;

  stack create();       // make a new stack
  void destroy(stack s);    // delete s

  void push(stack s, char c); // push c onto s
  char pop(stack s);      // pop s

The declaration

struct Rep;

says that Rep is the name of a type, but it leaves the type to be defined later. The declaration

typedef Rep& stack;

gives the name stack to a "reference to Rep." The idea is that a stack is identified by its Stack::stack and that further details are hidden from users.

A Stack::stack acts much like a variable of a built-in type:

struct Bad_pop { };

void f()
  Stack::stack s1 = Stack::create(); // make a new stack
  Stack::stack s2 = Stack::create(); // make another new stack


  if (Stack::pop(s1) != 'c') throw Bad_pop();
  if (Stack::pop(s2) != 'k') throw Bad_pop();


We could implement this Stack in several ways. It is important that a user doesn't need to know how we do it. As long as we keep the interface unchanged, a user will not be affected if we decide to re-implement Stack.

An implementation might preallocate a few stack representations and let Stack::create() hand out a reference to an unused one. Stack::destroy() could then mark a representation "unused" so that Stack::create() can recycle it:

namespace Stack {     // representation

  const int max_size = 200;

  struct Rep {
   char v[max_size];
   int top;

  const int max = 16;  // maximum number of stacks

  Rep stacks[max];   // preallocated stack representations
  bool used[max];    // used[i] is true if stacks[i] is in use

  typedef Rep& stack;

void Stack::push(stack s, char c) { /* check s for overflow and push c */ }

char Stack::pop(stack s) { /* check s for underflow and pop */ }

Stack::stack Stack::create()
  // pick an unused Rep, mark it used, initialize it, and return a reference to it
void Stack::destroy(stack s) { /* mark s unused */ }

What we have done is to wrap a set of interface functions around the representation type. How the resulting "stack type" behaves depends partly on how we defined these interface functions, partly on how we presented the representation type to the users of Stacks, and partly on the design of the representation type itself.

This is often less than ideal. A significant problem is that the presentation of such "fake types" to the users can vary greatly depending on the details of the representation type—and users ought to be insulated from knowledge of the representation type. For example, had we chosen to use a more elaborate data structure to identify a stack, the rules for assignment and initialization of Stack::stacks would have changed dramatically. This may indeed be desirable at times. However, it shows that we have simply moved the problem of providing convenient stacks from the Stack module to the Stack::stack representation type.

More fundamentally, user-defined types implemented through a module providing access to an implementation type don't behave like built-in types and receive less and different support than do built-in types. For example, the time that a Stack::Rep can be used is controlled through Stack::create() and Stack::destroy() rather than by the usual language rules.

2.5.2 User-Defined Types

C++ attacks this problem by allowing a user to directly define types that behave in (nearly) the same way as built-in types. Such a type is often called an abstract data type. I prefer the term user-defined type. A more reasonable definition of abstract data type would require a mathematical "abstract" specification. Given such a specification, what are called types here would be concrete examples of such truly abstract entities. The programming paradigm becomes this:

Decide which types you want; provide a full set of operations for each type.

Where there is no need for more than one object of a type, the data-hiding programming style using modules suffices.

Arithmetic types such as rational and complex numbers are common examples of user-defined types. Consider:

class complex {
  double re, im;
  complex(double r, double i) { re=r; im=i; } // construct complex from two scalars
  complex(double r) { re=r; im=0; }      // construct complex from one scalar
  complex() { re = im = 0; }         // default complex: (0,0)

  friend complex operator+(complex, complex);
  friend complex operator-(complex, complex); // binary
  friend complex operator-(complex);     // unary
  friend complex operator*(complex, complex);
  friend complex operator/(complex, complex);

  friend bool operator==(complex, complex);  // equal
  friend bool operator!=(complex, complex);  // not equal
  // ...

The declaration of class (that is, user-defined type) complex specifies the representation of a complex number and the set of operations on a complex number. The representation is private; that is, re and im are accessible only to the functions specified in the declaration of class complex. Such functions can be defined like this:

complex operator+(complex a1, complex a2)
  return complex(a1.re+a2.re,a1.im+a2.im);

A member function with the same name as its class is called a constructor. A constructor defines a way to initialize an object of its class. Class complex provides three constructors. One makes a complex from a double, another takes a pair of doubles, and the third makes a complex with a default value.

Class complex can be used like this:

void f(complex z)
  complex a = 2.3;
  complex b = 1/a;
  complex c = a+b*complex(1,2.3);
  // ...
  if (c != b) c = -(b/a)+2*b;

The compiler converts operators involving complex numbers into appropriate function calls. For example, c!=b means operator!=(c,b) and 1/a means operator/(complex(1) ,a).

Most, but not all, modules are better expressed as user-defined types.

2.5.3 Concrete Types

User-defined types can be designed to meet a wide variety of needs. Consider a user-defined Stack type along the lines of the complex type. To make the example a bit more realistic, this Stack type is defined to take its number of elements as an argument:

class Stack {
  char* v;
  int top;
  int max_size;
  class Underflow { };   // used as exception
  class Overflow { };   // used as exception
  class Bad_size { };   // used as exception

  Stack(int s);      // constructor
  ˜Stack();        // destructor

  void push(char c);
  char pop();

The constructor Stack(int) will be called whenever an object of the class is created. This takes care of initialization. If any cleanup is needed when an object of the class goes out of scope, a complement to the constructor—called the destructor—can be declared:

Stack::Stack(int s)  // constructor
  top = 0;
  if (s<0 || 10000<s) throw Bad_size(); // "||" means "or"
  max_size = s;
  v = new char[s];  // allocate elements on the free store (heap, dynamic store)

Stack::˜Stack()    // destructor
  delete[] v;     // free the elements for possible reuse of their space

The constructor initializes a new Stack variable. To do so, it allocates some memory on the free store (also called the heap or dynamic store) using the new operator. The destructor cleans up by freeing that memory. This is all done without intervention by users of Stacks. The users simply create and use Stacks much as they would variables of built-in types. For example:

Stack s_var1(10);        // global stack with 10 elements

void f(Stack& s_ref, int i)   // reference to Stack

  Stack s_var2(i);       // local stack with i elements
  Stack* s_ptr = new Stack(20); // pointer to Stack allocated on free store

  s_var1.push('a');       // access through variable
  s_ref.push('c');       // access through reference
  s_ptr->push('d');       // access through pointer
  // ...

This Stack type obeys the same rules for naming, scope, allocation, lifetime, etc., as does a built-in type such as int and char.

Naturally, the push() and pop() member functions must also be defined somewhere:

void Stack::push(char c)
  if (top == max_size) throw Overflow();
  v[top] = c;
  top = top + 1;

char Stack::pop()
  if (top == 0) throw Underflow();
  top = top - 1;
  return v[top];

Types such as complex and Stack are called concrete types, in contrast to abstract types, where the interface more completely insulates a user from implementation details.

2.5.4 Abstract Types

One property was lost in the transition from Stack as a "fake type" implemented by a module (§2.5.1) to a proper type (§2.5.3). The representation is not decoupled from the user interface; rather, it is a part of what would be included in a program fragment using Stacks. The representation is private, and therefore accessible only through the member functions, but it is present. If it changes in any significant way, a user must recompile. This is the price to pay for having concrete types behave exactly like built-in types. In particular, we cannot have genuine local variables of a type without knowing the size of the type's representation.

For types that don't change often, and where local variables provide much-needed clarity and efficiency, this is acceptable and often ideal. However, if we want to completely isolate users of a stack from changes to its implementation, this last Stack is insufficient. Then, the solution is to decouple the interface from the representation and give up genuine local variables.

First, we define the interface:

class Stack {
  class Underflow { };   // used as exception
  class Overflow { };    // used as exception

  virtual void push(char c) = 0;
  virtual char pop() = 0;

The word virtual means "may be redefined later in a class derived from this one" in Simula and C++. A class derived from Stack provides an implementation for the Stack interface. The curious =0 syntax says that some class derived from Stack must define the function. Thus, this Stack can serve as the interface to any class that implements its push() and pop() functions.

This Stack could be used like this:

void f(Stack& s_ref)
  if (s_ref.pop() != 'c') throw Bad_pop();

Note how f() uses the Stack interface in complete ignorance of implementation details. A class that provides the interface to a variety of other classes is often called a polymorphic type.

Not surprisingly, the implementation could consist of everything from the concrete class Stack that we left out of the interface Stack:

class Array_stack : public Stack {  // Array_stack implements Stack
  char* p;
  int max_size;
  int top;
  Array_stack(int s);

  void push(char c);
  char pop();

The ":public" can be read as "is derived from," "implements," and "is a subtype of."

For a function like f() to use a Stack in complete ignorance of implementation details, some other function will have to make an object on which it can operate. For example:

void g()
  Array_stack as(200);

Since f() doesn't know about Array_stacks but only knows the Stack interface, it will work just as well for a different implementation of a Stack. For example:

class List_stack : public Stack { // List_stack implements Stack
  list<char> lc;         // (standard library) list of characters
  List_stack() { }

  void push(char c) { lc.push_front(c); }
  char pop();
char List_stack::pop()
  char x = lc.front();     // get first element
  lc.pop_front();        // remove first element
  return x;

Here, the representation is a list of characters. The lc.push_front(c) adds c as the first element of lc, the call lc.pop_front() removes the first element, and lc.front() denotes lc's first element.

A function can create a List_stack and have f() use it:

void h()
  List_stack ls;

2.5.5 Virtual Functions

How is the call s_ref.pop() in f() resolved to the right function definition? When f() is called from h(), List_stack::pop() must be called. When f() is called from g(), Array_stack::pop() must be called. To achieve this resolution, a Stack object must contain information to indicate the function to be called at run-time. A common implementation technique is for the compiler to convert the name of a virtual function into an index into a table of pointers to functions. That table is usually called "a virtual function table" or simply, a vtbl. Each class with virtual functions has its own vtbl identifying its virtual functions. This can be represented graphically like this:

The functions in the vtbl allow the object to be used correctly even when the size of the object and the layout of its data are unknown to the caller. All the caller needs to know is the location of the vtbl in a Stack and the index used for each virtual function. This virtual call mechanism can be made essentially as efficient as the "normal function call" mechanism. Its space overhead is one pointer in each object of a class with virtual functions plus one vtbl for each such class.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020