C++ Overview by John Tal 1.0 C++ and C C++ is an object-oriented extension to the C language. C++ can be used to compile C programs. Everything you can do in C, you can also do in C++. C++ programs and their extensions cannot be compiled under a C only compiler. 2.0 Object-Oriented Programming 2.1 Class The class concept is the fundamental building block for all objected-oriented programming systems (OOPS). A class consists of an object (or group of objects) and the function(s) which operate on the obects(s). In C++, a class is defined in a similar way to a structure, except the keyword class is used: class FILE_C; // forward reference to a class 2.2 Class Components A class definition contains declarations for variables and functions. A class definition also provides different security areas for variables and functions. class FILE_C { private: long ptr; // file pointer char name[FNAME_LEN]; // file name short state; // file state short mode; // file mode public: FILE_C(void); // class constructor ~FILE_C(void); // class destructor short Open(char *,short); // open function short Close(void); // close function short Read(char *,short); // read function short Write(char *,short); // write function }; The above FILE_C class has four private data items (objects) and six functions which operate on those objects. Any access to the class objects must occur through a class function. The private keyword enforces this data hiding by preventing the application using the class from having access to anything in the class private area. Only the class functions themselves can access private objects. 2.3 Class Constructors And Destructors The FILE_C class has a FILE_C() function as a constructor and a ~FILE_C() function as a destructor. The constructor is a function with the same name as the class which is invoked at the creation of an instance of the class and is intended to provide any initialization the class requires. The destructor function also has the same name as the class but with a '~' (tilde) character in front of it. A destructor is provided for any cleanup work to occur within the class at the termination of the class instance (such as making sure the file is closed). A class instance is created in two different ways. The first is by declaring a class instance in the same way a standard C language variable is created. short x; // create a variable named x FILE_C LogFile; // create a unique instance of the FILE_C class The second method of creating a class instance is by allocating a new instance through a pointer and the new keyword. FILE_C * pLogFile; // create a pointer to a FILE_C class pLogFile = new FILE_C; // create an instance and assign ptr The new keyword is provided as an improved calloc or malloc. The new keyword calculates the size of the memory block to be allocated to the item being created. 2.3.1 Constructors With Parameters Like any function, a constructor can take parameters. The parameters would be supplied at the time of the creation of a new class instance. class FILE_C { ... public: FILE_C(char *pFileName); }; FILE_C LogFile("LogFileName"); // constructor with parm 2.4 Class Function Calling Class member functions are called like normal C functions. The difference is that they use syntax similar to that used for structure membership. FILE_C LogFile; // create instance of FILE_C FILE_C * pInputFile; // create ptr to instance of FILE_C pInputFile = new FILE_C; // create instance of FILE_C LogFile.Open("LogFile",O_APPEND); // open LogFile InputFile -> Open("InputDat",O_READONLY); // open InputFile InputFile -> Read(buffer,sizeof(buffer)); // read InputFile From the above example, a file pointer is never sent to the FILE_C functions as would be in standard C file functions. This is because each instance of the FILE_C maintains its own control information internal to the class itself in its own private area. C++ usually simplifies interfaces between classes and applications because classes are complete in themselves. They contain all the attributes and/or objects that describe the class within. 2.5 Class Function Declaration A class definition (such as class FILE_C ...) would occur in an include file. The actual functions of the class would be declared in a C++ source file. Each class function is prefixed with the class name to which it belongs and the symbol '::'. short FILE_C::Open(char * pFileName,short mode) { mode = mode; // referencing private data item strcpy(name,pFileName); // perform open return (status); } 2.6 Inline Functions If a class function is performing a very simple task, it can be declared an an inline function. An inline function is an expanded version of the function declaration within the class with begin and end braces surronding the inline statement(s). class FILE_C { private: char name[FNAME_LEN]; // file name ... public: FILE_C(char *pFileName) { strcpy(name,pFileName); } ... }; The above example shows the FILE_C constructor implemented as an inline function. Inline functions should be limited to functions having only a few (preferrably one) statement(s). 3.0 Derived Classes One of C++' most powerful features is to use classes as building blocks in creating entirely new classes. class BROWSE_C : FILE_C // browse derived from file { private: short curline; ... public: BROWSE_C(void); ~BROWSE_C(void); OpenFile(char *); }; From the above example, the BROWSE_C class will have access not only to all of its own member data/objects, but also to all FILE_C class member functions which were declared as public or protected in FILE_C. The following table breaks down class security areas for immediate classes and derived classes. Immediate Derived ---------- --------- Private Not-visible in derived class Protected Visible as Private in derived Public Visible as Protected in derived From the above example, the BROWSE_C class would be able to access any data and functions which were defined as protected or public in the FILE_C class. The application would not be able to access any of the data or functions of the FILE_C class without going through a public member function of the BROWSE_C class. These are the default security inheritance protocols for classes. 3.1 Customizing Class Inheritance The default security inheritance can be overridden when defining the derived class: class BROWSE_C : public FILE_C // browse derived from file { private: short curline; ... public: BROWSE_C(void); ~BROWSE_C(void); OpenFile(char *); }; From the above example, all public functions of FILE_C class are also public to applications using the BROWSE_C class. 3.2 Container Classes Container classes are classes which contain other classes. An example would be a class to implement a binary tree: class TREE_C { private: struct TNODE_S // the contained class { PVOID pvData; struct TNODE_S *pstLeft; struct TNODE_S *pstRight; }; typedef struct TNODE_S TNODE_T; typedef TNODE_T *TNODE_P; typedef TNODE_T **TNODE_PP; TNODE_P pstHead; TNODE_P pstNode; ... public: TREE_C(VOID); ~TREE_C(VOID); SHORT Delete(PVOID); // Remove entry SHORT Find(PVOID,PPVOID); // Find entry SHORT Insert(PVOID); // Insert entry ... }; typedef TREE_C * TREE_CP; typedef TREE_C ** TREE_CPP; In the binary tree example, it was not desirable for each node of the tree to be an instance of the TREE_C class. So each node is contained in the TREE_C class and the TREE_C class operates on all the TNODE_S structures/classes contained within it. 3.3 Virtual Functions Virtual functions provide a way for a base class function to take on the characteristics or behavior appropriate to the current derived class. class FILE_C { private: char name[FNAME_LEN]; // file name ... public: FILE_C(char *pFileName) { strcpy(name,pFileName); } virtual short Reset(void); }; class BROWSE_C : FILE_C // browse derived from file { private: short curline; ... public: BROWSE_C(void); ~BROWSE_C(void); OpenFile(char *); short Reset(void); }; short BROWSE_C::Reset(void) { FILE_C::Reset(); curline = 0; } 4.0 Operator Overloading Since C++ classes define in detail the characters of and operations upon the class instance, C++ allows all standard operators (i.e. '+', '-', '*', '/', '++', '--') to be redefined or overloaded for the current class. class STRING_C { private: char * pChar; int len; ... public: STRING_C(const char * = 0); // provide default value ~STRING_C(delete pChar); void operator+(char *) }; STRING_C::operator+(char *pC) { char * pBuf; pBuf = new char[len=strlen(pC)+len]; strcpy(pBuf,pChar); strcat(pBuf,pC); delete pChar; pChar = pBuf; } STRING_C Str("ABC"); Str + "DEF"; // internal pChar now = 'ABCDEF' Operator overloading still involves functions to simulate the operator being overloaded. Overloading simply provides a mechanism for abbreviating the operations. 5.0 C++ Input/Output C++ output is simplified over that of C printf family functions. C++ defines the keywords cout and cin and the stdout and stdin devices. C++ automatically formats the output based on the current variable type. /* In C */ printf("%s = %d\n", szRate, sRate); // In C++ cout << szRate << " = " << sRate << "\n"; // Another C++ alternative cout << form("%s = %d\n", szRate,sRate); /* In C */ scanf("%d",&sRate); // In C++ cin >> sRate; 7.0 Reference Variables C++ provides a syntax which allows programmers who are not comfortable with C pointer syntax to more easily write applications which use pointers. /* In C */ short Afunc(short * psShort) { *psShort++; } // In C++ short Afunc(short & Short) { Short++; }