11.07.2015 Views

Encyclopedia of Computer Science and Technology

Encyclopedia of Computer Science and Technology

Encyclopedia of Computer Science and Technology

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

68 C++While attracted to the advantages <strong>of</strong> the object-orientedapproach, Stroustrup also wanted to preserve the Clanguage’s ability to precisely control machine behaviorneeded for systems programming. He thus decided to builda new language on C’s familiar syntax <strong>and</strong> features withobject-oriented extensions. Stroustrup wrote the first version,called “C with Classes” as his Ph.D. thesis at CambridgeUniversity in Engl<strong>and</strong>. This gradually evolved intoC++ through the early 1980s.C++ FeaturesThe fundamental building block <strong>of</strong> C++ is the class. A classis used to create objects <strong>of</strong> its type. Each object containsa set <strong>of</strong> data <strong>and</strong> can carry out specified functions whencalled upon by the program. For example, the followingclass defines an array <strong>of</strong> integers <strong>and</strong> declares some functionsfor working with the array. Typically, it would be putin a header file (such as stack.h):const int Max_size=20; // maximum elementsin Stackclass Stack { // Declare the Stack classpublic: // These functions are availableoutsideStack(); // Constructor to create Stackobjectsvoid push (int); // push int on Stackint pop(); // remove top elementprivate: // This data can only be used inclassint index;int Data[Max_size];};Next, the member functions <strong>of</strong> the Stack class aredefined. The definitions can be put in a source file Stack.cpp:#include “Stack.h” // bring in the declarationsStack::Stack() { index=0;} // set zero fornew stackvoid Stack::push (int item) { // put a numberon stackData[index++] = item;}int Stack::pop(){ // remove top numberreturn Data [index–];}Now a second source file (Stacktest.cpp) can be written.It includes a main() function that creates a Stack object <strong>and</strong>tests some <strong>of</strong> the class functions:#include “Stack.cpp” // include the Stackclass#include // include st<strong>and</strong>ard I/Olibrarymain() {Stack S; // Create a Stack object called Sint index;for (index = 1; index

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!