3.1. C++ as a better C
Comments // one line comments ------- /* Traditional comments can be used for multi-line description */ Class User defined data type class shape { ----- describing not only data structure, int x; but also operations upon the data, int y; called member functions or methods. shape();//constructor ~shape();//destructor }; Declaration within a block is allowed in C++ in any place: --------------------------------------------------------- for( int i = 0;...) while C only allows declarations before the first executable operator. Const specifier -------------- int myCompare(const char *string1,const char *string2); Insures that values (in this case: string1 and string2) can not be changed by the (myCompare) operation. Pass parameters by reference --------------------------- void func( int &i) {i++} int main() { int b = 3: func( b ); } // b = 4 !!! Example in C Example in C++ int a; int a; typedef void* PVoid; typedef void* PVoid; typedef int* Pint; typedef int* PInt; PVoid v_ptr; PVoid v_ptr; . . . . . . a = ( int * )v_ptr; a = PInt( v_ptr); Inline specifier --------------- inline int InLineFunc( int x ) { return x*x*x ;} Function prototype is obligatory ------------------------------- void DrawCircle(int x, int y, int r); as a part of ANSI C - standard to reinforce type checking Default values for function parameters ------------------------------------ void DrawCircle( int x= 400, int y = 400, int rad = 100); Possible calls: DrawCircle( 200 ); // x=200; y=400; rad=100 DrawCircle( 300. 100 ); // x=300; y=100; rad=100 DrawCircle( , , 300 ): // x=400; y=400; rad=300 Pointer to void and functions that return void ---------------------------------------------- void* var1; void* funct();// prototype New and delete operators ------------------------ int* p_int; double* p_double; . . . . . . . . p_int = new int(10); p_double = new double(56); . . . . . delete p_int; delete p_double;
3.2. C++ supports OOP
3.3. Writing C++ sources: Programming Style Recommendations
3.4 Avoid common C++ mistakes (Examples of a C++ wrong code implementation)
3.5. Rogue Wave Tools.h++ (The industry standard library of classes)
Back To Software Technology Overview
3.1. C++ as a better C with Explanations and ExamplesBack To C++
3.2. C++ supports OOP Class as basic instrument for encapsulation Constructor and Destructor Private, protected and public sections Objects and methods Friends: allow access to private data Overloading: allows operators to be extended into specialized domains Derived classes and virtual functions support polymorphism The stream library with cin/cout/cerr classes simplifies I/O Back To C++
Object Oriented Concepts in pictures and examples
Back To Software Technology Overview
3.3. Writing C++ sources: Programming Style Recommendations Programs that are developed according to these rules and recomendations should be: - correct - easy to maintain In order to reach these goals, the programs should: - have a consistent style, - be easy to read and understand, - be portable to other architectures, - be free of common types of errors, - be maintainable by different programmers. To gain insight: - study the code Fine line between a feature and a bug. Code allows you to write compact (unreadable) code Rules, Exceptions, and Recommendations: Rule: Everytime a rule is broken, it must be clearly documented Example: class seecomment { int myname; // I broke a rule- I forgot to write private: }; Exceptions to Rule 0? Risk of being misunderstood by: a. The compiler b. Yourself c. The next programmer d. The teacher e. All of the above++ General Recommendations Rec.1. Optimize code only if you have a performance problem. Think twice before you begin!! (try using gproff++ to determine the nature of a problem) Rec.2. If you use a C++ compiler that is based on Cfront, compile with the +w flag set to eliminate as many warnings as possible. Rec.3. Structure Code in Files Purpose: To provide a uniform interpretation of file names. It is easier to make tools which base their behavior on file name extentions. Recognize 2 kinds of include files: 1. Contain code accepted by both ANSI C and C++ compilers. 2. Those that contain code only accepted by C++ compilers. Rule: Include files in C++ should have the extention ".hh". Exception: Include files which contain code accepted by C and C++ (both)compilers should have the file name extention ".h". If only C++ files are used the extension ".h" is acceptable. Rule: Implementation files in C++ should have extention "cc" or "cpp" Exception: When using UNIX the extension ".C" can be used. Rule: Inline definition files always have extention ".icc". No exceptions. Example: // AnyClass.hh #ifndef OUTLINE #include "AnyClass.icc" #endif //AnyClass.cc #ifdef OUTLINE #define inline #include "AnyClass.icc" #undef inline #endif Rec. 4 An include file should contain only one class definition. Example- // employee.hh #ifndef EMPLOYEE_H #define EMPLOYEE_H class employee { protected: char* ssn; // social security number char* ename; // employee name public: void Add(); // add a new employee }; #endif Rec. 5 Divide up the definitions of member functions into as many files as possible. Rec. 6 Place machine-dependent code in a special file so that it may be easily located when porting code to another machine. Naming Files Rec. 7 Always give a file a unique name in as large a context as possible. Rec. 8 An include file for a class should have a file name in the form+ extention. Use uppercase and lowercase letters same as source name. Example- // hourly.hh #ifndef HOURLY_H #define HOURLY_H #include "employee.hh" class hourly: public employee { protected: double hourlyRate; int workHours; public: void ComputePayCheck(); }; #endif Rule: Every file that contains source code must be documented with an introductory comment in English that provides the information on the file name and its contents. Every function should have a brief explanation-header. No exceptions. Example- /**************************************************** Author: Jeff Zhuk Date: 07/03/95 Module: payroll.cpp Description: This module is the main program for the PAYROLL project. It represents EMPLOYEE - related menu and prompts the user for ................................... **********************************/ Rec. 9 Use // for one line comments Use /* for multy-line (more then 2 lines) comments */ Rule: Every include file must contain a mechanism that prevents multiple inclusions of the file. Example: #ifndef EMPLOYEE_H #define EMPLOYEE_H ........... #endif Rule: When the following kinds of definitions are used (in implementation files or in other include files), they must be included as seperate include files: - classes that are used as base classes - classes that are used as member variables - classes that appear as return types or as argument types in function/member function prototypes. - function prototypes for functions used in inline member functions that are defined in the file. Rule: Definitions of classes that are only accessed via pointers (*) or references (&) shall not be included as include files. Rule: Never specify relative UNIX names in #include directives. Example: // Not recommended #include <../include/fnutt.hh> // Not guaranted to work #include < sys/socket.hh> Rule: Every implementation file is to include the files that contain: - declarations of types and functions used in the functions that are implemented in the file. - declarations of variables and member functions used in the functions that are implemented in the file. Rec. 10 Use the directive: #include "fileName.hh" for user prepared include files. Rec. 11 Use the directive: #include < fileName.hh> for include files from libraries.
Back To C++
Back To Software Technology Overview
Examples of a C++ wrong code implementation . . Instructor Jeff Zhuk
- Constructor and Deconstructor
class starChild { private: int veryGood; public: int starChild::starChild() { verygood=1;} // Error -> Constructor cannot // return a value. };
class C { int x; int y; public: int C ( ); // This constructor would cause an error because // it has a return type. Constructors must meet 2 // conditions to be valid: no return value and the // constructor name same as the class name. ... ... ... };
class x // not a good style, better to Capitalize { // class name ! private: int x; // confusing ! variable name as a class name int y; public: XX(){ }; // compiler error; // method is not a constructor // It must have a return value. }
- Private, protected and public sections
class starChild { private: int veryGood = 1; // Cannot be initialized in this manner. // Must be done via constructor or other // member function. public: int returnHighIQ(); starChild:starChild (startChild); // Error -&bg Constructor cannot take as parameter an object // itself. The correct way to do this would be by making the // parameter a reference (starChild). This would be the dec- // laration for a copy constructor. private: int highIQ; };
class Kathy { public: int (int num); ~Kathy(void); void display(); private: char *title; int rec_number; protected: void showError(); // method in protected area - limited access. }; ... ... count << "Enter title of CD " << end1; cin >> title >> end1; // cannot access private member 'title'. count << "Enter CD identification" << end1; cin >> rec_number >> end1; // cannot access private member 'rec_number'. // Both 'title' and 'rec_number' have to be accessed a different way - could // create a public method that could be called to access private attributes.
class A { // base class protected: int x; ine y; public: void print(int x,int y); void add (int x, int y); void subtr ( int x, int y); A ( ); ~A ( ); }; class B: public A { // derived class private: int A; int B; public: void print ( int x, int y); void add ( int x, int y); void substr (int x, int y); B ( ); ~B ( ); }; main { A A_type; cout << int x = << A_type << end1; // THis is error because 'x' is only accessable to the class methods. // The correct way would be to invoke the print method: A_type.print(3,4).
class X { private: int x; protected: int y; public: int z; void display (int x, int y, int z); ... main { X ob1; ob1.display(5,8,10); // Runtime error.'x' is a private. ...
- Derived classes
class B { private: int x; protected: int y; public: void show(int x, int y); }; class D : public B { private: int z; public: void show (int): } main ( ) { B b_ob; D d_ob; d_od.show (x,y); // runtime error. 'x' is private and not accessable to D. ...
class rock { private: int diamond; int ruby; int amber; public: rock:: rock ( diamond = 1; ruby = 2; amber = 100); showAll (); }; class dirt : public rock { private: int sand; public: dirt :: dirt(); }; main () { dirt t; dirt *ptr_d; ptr_d = &d; ptr_d ->ruby = 5; // Error: ruby is not visible in derived class. ...
- Polymorphism
class rock { private: int diamond; public: rock::rock(); virtual int grindToDirt(): }; class dirt { private: int sand; public: int grindToDirt(): }; main () { rock r; dirt d; dirt *ptr_d; ptr_d = &d; ptr->grindToDirt(): ptr_d = &r; // Error: cannot take on the address of base class (not // without a cast). ...
class Shape { // assume it's a base class for // polymorphic usage of area() method in derived // Circle and Square classes public: float area (); // incorrect - needs keyword "virtual" before // float in order for subclass to inherit and use // polymorphically. }; class Circle : public Shape { public: float area(int radius); // incorrect: }; // must be same prototype // as in the base class class Square { // incorrect - derived class must // have "public Shape" after "class // Square" to inherit from base class. public : float (area(int height, int width);// incorrect: // must be same prototype // as in the base class };
class B { protected: char *name; char * address; int age; public: int getAge(int); void Show(); }; class D : public B { protected: int grade; public: int getGrade(); void Show(); }; main () { B *b; D *d; b->Show(); // runtime error: need virtual keyword. d->Show(); ...
Back To C++
Back To Software Technology Overview