Introduction to C Programming Module 1 An Overview

























- Slides: 25

Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph. D. Department of Computing Sciences University of Scranton (717)941 -6108 bi@cs. uofs. edu

Outline z Module 1 - An Overview of C++ and OO Programming z Module 2 - Classes and Operator Overloading z Module 3 - Inheritance and Dynamic Binding z Module 4 - Function and Class Templates z Module 5 - C++ Stream I/O and Exception Handling 1/15/2022 August 13, 1998 bi@cs. uofs. edu 2

History z Developed by Bjarne Stroustrup at AT&T, 1986. z Originally called “C++ with classes” z C++: Enhanced version of C. y Stronger type checking y Support for data abstraction y Support for OO programming y Support for Generic programming z C++ is a superset of C. z ISO/ANSI C++ Standard, 1998 1/15/2022 August 13, 1998 bi@cs. uofs. edu 3

Example 1: A Simple C++ Program // Convert miles to kilometers #include <iostream. h> z New Comment Style const double m_to_k = 1. 609; inline double convert(double mi) { return (mi *m_to_k); } z iostream. h file y // Convert. . . int main() { double miles; cout << "Input distance in miles: "; cin >> miles; cout<<"n. Distance: "<< convert(miles) << " km. " << endl; return 0; } 1/15/2022 August 13, 1998 y C++ stream I/O z Keyword const y constant variable z Keyword inline y inline code if possible z Input/output y cin >> and cout << z Stream manipulator y endl (end line) = “n” bi@cs. uofs. edu 4

Example 2: Reference Parameters and Function Overloading //function. cpp #include <iostream. h> void square(int*); void sqr. By. Ref(int&); void sqr. By. Ref(double&); //by pointer //by reference //overloaded int main() { int num = 3; square(&num); //square(int*) cout <<"by pointer (int*): " << num << endl; int r. Num =4; sqr. By. Ref(r. Num); //sqr. By. Ref(int&) 1/15/2022 August 13, 1998 cout <<"by reference (int): " << r. Num << endl; double dbl = 3. 5; sqr. By. Ref(dbl); //sqr. By. Ref(double&) cout <<"by reference (double): " << dbl << endl; return 0; } // end of main void square(int* sqr) { *sqr = (*sqr) * (*sqr); } void sqr. By. Ref(int& sqr) { sqr = sqr * sqr; } void sqr. By. Ref(double& y) { y = y*y; } bi@cs. uofs. edu 5

Example 2: function -- Cont’d z Function declaration y A function must be declared before it is used. void square(int*); // prototype z Pass by reference y A reference is a alias of the variable. sqr in sqr. By. Ref(int&) is an alias for r. Num in main() z Variable declaration y A variable may be declared when it is used. z Function overloading y several functions have the same name void sqr. Bt. Ref(int&); and void sqr. By. Ref(double&); y distinguished with different parameter lists. int& for the first and double& for the second y Compiler finds the right one int r. Num; 1/15/2022 August 13, 1998 bi@cs. uofs. edu 6

Example 3: A Stack Class //Class Specification // Stack. h const int max. Size = 10; //Class Implmentation // stack. cpp #include <iostream. h> #include "Stack. h" class CStack { public: // public interface CStack(int sz = max. Size); // constructor void Push (int item); int Pop(); bool Is. Empty() const; bool Is. Full() const; ~CStack(); // Destructor private: // private implementation int* m_Array; int m_n. Top; int m_n. Size; }; 1/15/2022 August 13, 1998 CStack: : // class scope oeprator CStack(int sz) { m_Array = new int[sz]; m_n. Size = sz; m_n. Top = -1; } CStack: : ~CStack() { delete [] m_Array; } bi@cs. uofs. edu 7

Example 3: Stack - cont’d // stack. cpp - continued // class. cpp void CStack: : Push(int item) { m_Array[++m_n. Top] = item; } int CStack: : Pop() { return m_Array[m_n. Top--]; } bool CStack: : Is. Empty() const { return (m_n. Top < 0); } bool CStack: : Is. Full() const { return (m_n. Top == m_n. Size - 1); } #include <iostream. h> #include "Stack. h" 1/15/2022 August 13, 1998 void main() { CStack stack; for ( int i = 1; i < max. Size+3; i++) { if (!stack. Is. Full()) stack. Push(i*100); } while (!stack. Is. Empty()) { cout << stack. Pop() << endl; } } bi@cs. uofs. edu 8

Example 3: Stack - cont’d z Information Hiding ypublic interface and private implementation- When the private implementation is changed, the users of the class do not need to change. z Constructor: y. It is executed when an object of the class is created. y. Initialize the object z Destructor: y. It is executed when an object of the class is destroyed. y. Clean up 1/15/2022 August 13, 1998 bi@cs. uofs. edu 9

Example 4: Class and Function Templates // stack. Tmpl. h // stack. cpp const int max. Size = 10; #include <iostream. h> #include "stack. Tmpl. h" template <class T> template<class T> class CStack<T>: : CStack(int sz) { { m_Array = new T[sz]; public: // public interface m_n. Size = sz; CStack(int sz = max. Size); m_n. Top = -1; void Push (const T& item); }; T Pop(); template<class T> void CStack<T>: : Push(const T& item) bool Is. Empty() const; { bool Is. Full() const; m_Array[++m_n. Top] = item; ~CStack(); }; private: // private implementation template<class T> T* m_Array; T CStack<T>: : Pop() { int m_n. Top; return m_Array[m_n. Top--]; int m_n. Size; }; }; 1/15/2022 August 13, 1998 bi@cs. uofs. edu 10

Example 4: Templates -- cont’d // stack. Tmpl. cpp -- cont’d template<class T> bool CStack<T>: : Is. Empty() const { return (m_n. Top < 0); }; template<class T> bool CStack<T>: : Is. Full() const { return (m_n. Top == m_n. Size - 1); }; template<class T> CStack<T>: : ~CStack() { delete [] m_Array; }; // template. cpp ---- Main function #include <iostream. h> #include "stack. Tmpl. cpp" template <class T> void Print(CStack<T>& stack); 1/15/2022 August 13, 1998 void main() { CStack<int> istack; CStack<char> cstack; } for ( char i = ’A'; i < ’A'+10; i++) { if (!istack. Is. Full()) istack. Push(int(i)); if (!cstack. Is. Full()) cstack. Push(i); } Print(istack); Print(cstack); template<class T> void Print(CStack<T>& stack) { while (!stack. Is. Empty()) { cout << stack. Pop() << endl; } } bi@cs. uofs. edu 11

Example 4: Templates -- cont’d z Class Templates z Function Templates y Template definition template <class T> class CStack { public: CStack(int sz = max. Size); void Push (const T& item); . . . private: T* m_Array; … }; y Template instantiation // stack of integer CStack<int> i. Stack; // stack of double CStack<double> d. Stack; // stack of char CStack<char> c. Stack; 1/15/2022 August 13, 1998 y Template definition template<class T> void Print(CStack<T>& stack) { while (!stack. Is. Empty()) { cout << stack. Pop() << endl; } } y Template instantiation // stack of integer CStack<int> i. Stack; // stack of double CStack<double> d. Stack; // stack of char CStack<char> c. Stack; bi@cs. uofs. edu 12

Example 5: Inheritance and Dynamic Binding z CPerson y Parent class z CManager & CEngineer y Child classes y “is-a” CPerson y Inherit all the operations and attributes of CPerson z Print() y virtual function y Redefined in child classes y Dynamic binding 1/15/2022 August 13, 1998 bi@cs. uofs. edu 13

Example 5: Inheritance //person. h //person. cpp #include <iostream> #include "person. h" using namespace std; #ifndef PERSON_H #define PERSON_H #include <string> using namespace std; class CPerson { public: CPerson(const string name, int age = 30); ~CPerson(); string Get. Name() const; int Get. Age() const; void Set. Name(string); void Set. Age(int); virtual void Print() const; private: string m_name; int m_age; }; #endif 1/15/2022 August 13, 1998 CPerson: : CPerson(string name, int age) : m_name(name), m_age(age) {} CPerson: : ~CPerson() {} string CPerson: : Get. Name() const { return m_name; } int CPerson: : Get. Age() const { return m_age; } void CPerson: : Set. Name(string name) { m_name = name; } void CPerson: : Set. Age(int age) { m_age = age; } void CPerson: : Print() const { cout << "Name: tt" << m_name << endl; cout << "Age: tt" << m_age << endl; } bi@cs. uofs. edu 14

Example 5: Inheritance -- cont’d //manager. h //manager. cpp #include <iostream> #include "manager. h" #ifndef MANAGER_H #define MANAGER_H #include "person. h" class CManager: public CPerson { public: CManager(string name, int age=25, int mgr. Level=1); ~CManager(); int Get. Mgr. Level() const; void Set. Mgr. Level(int level); virtual void Print() const; private: int m_n. Mgr. Level; }; #endif 1/15/2022 August 13, 1998 CManager: : CManager(string name, int age, int mgr. Level) : CPerson(name, age) { m_n. Mgr. Level = mgr. Level; } CManager: : ~CManager() { } int CManager: : Get. Mgr. Level() const { return m_n. Mgr. Level; } void CManager: : Set. Mgr. Level(int level) { m_n. Mgr. Level = level; } void CManager: : Print() const { CPerson: : Print(); cout << "Mngmnt Level: t" << m_n. Mgr. Level << endl; } bi@cs. uofs. edu 15

Example 5: Inheritance -- cont’d //engineer. h //engineer. cpp #include <iostream> #include "engineer. h" #ifndef ENGINEER_H #define ENGINEER_H using namespace std; #include "person. h" class CEngineer: public CPerson { public: CEngineer(string name, int age=25, int eng. Type = 1); ~CEngineer(); int Get. Eng. Type() const; void Set. Eng. Type(int eng. Type); virtual void Print() const; private: int m_n. Eng. Type; }; #endif 1/15/2022 August 13, 1998 CEngineer: : CEngineer(string name, int age, int eng. Type) : CPerson(name, age), m_n. Eng. Type(eng. Type) { } CEngineer: : ~CEngineer() { } int CEngineer: : Get. Eng. Type() const { return m_n. Eng. Type; } void CEngineer: : Set. Eng. Type(int eng. Type) { m_n. Eng. Type = eng. Type; } void CEngineer: : Print() const { CPerson: : Print(); cout << "Eng Type: t" << m_n. Eng. Type << endl; } bi@cs. uofs. edu 16

Example 5: Inheritance -- cont’d // inheritance. cpp -- cont’d //inheritance. cpp for (int i=0; i<3; i++) { array[i]->Print(); cout << endl; } return 0; #include <iostream> #include "manager. h" #include "engineer. h" int main() { CManager mngr 1("Bi"); //default values CManager mngr 2("Brown", 25, 20); CEngineer engineer("Smith", 20, 15); } // call an inherited function mngr 1. Set. Name("Johnson"); CPerson* array[3]; array[0] = &mngr 1; array[1] = &engineer; array[2] = &mngr 2; 1/15/2022 August 13, 1998 bi@cs. uofs. edu 17

1. C++ as a better C z C++ single-line comments y A common programming error is forgetting to close a c-style comment with “*/”. Using // can avoid that. z C++ stream I/O y #include <iostream. h> y cin>> for input and cout<< for output y less error prone z Declarations of variables y Don’t declare a variable until it can be initialized. y Introduce the variable into the smallest scope possible. z Inline functions y Prefer inline over #define Ex: inline int square(int); y should only be used for simple, small functions. y Reduce execution time, but increase program size. 1/15/2022 August 13, 1998 bi@cs. uofs. edu 18

1. C++ as a better C z Reference parameters y A reference is an alias for the variable it references to. y A reference must be initialized ex: int count; int& r. Count = count; r. Count = 100; // count = r. Count = 100 y Use const reference parameters for large objects. ex: 1/15/2022 August 13, 1998 void foo. By. Ref(const Type& r); void foo. By. Val(const Type r); . . Type y; foo. By. Ref(y); //in foo. By. Ref, r is a reference to y and // r cannot be modified in foo. By. Val(y) //in foo. By. Val(), a local r is created and //initialized with the value of y. The value //of y is copied to r, which can be expensive //when r is large. bi@cs. uofs. edu 19

1. C++ as a better C z The const qualifier y Prefer const over #define - const variables are visible to debuggers. const int Max. Size = 20; const char* ptr; // a pointer pointing to a const char* const ro. Ptr // a const pointer to a char z The new and delete operators In C++ Type* ptr = malloc(sizeof(Type)); Type* ptr = new Type; free(ptr); delete ptr; Ex: . . . int* ptr 1 = new int(200); // *ptr = 200 int* ptr 2 = new int[200]; // ptr is an array with 200 elements. delete ptr 1; // delete a single object delete [] ptr 2; // delete an array CStack* p. Stack = new CStack; // a new stack delete p. Stack; //delete stack - ~CStack called 1/15/2022 August 13, 1998 bi@cs. uofs. edu 20

1. C++ as a better C z Default arguments y provide a value for a argument int foo(int x, int y=10); . . . int z = foo(20); int w = foo(30, 20); // equal to foo(20, 10); // the passed overwrites the default y Default arguments must the rightmost arguments in the list. z Scope operator y When a local variable has the same name as a global variable, use : : to access the global variable. int value = 100; int main() { double value = 1. 234; cout << value; cout << : : value; . . . 1/15/2022 August 13, 1998 // global int value is not visible // print local value (double) - 1. 234; // print global value (int) - 100 bi@cs. uofs. edu 21

1. C++ as a better C z Function overloading y several functions have the same name with different signatures. y The signature of a function is: xparameter list y Return type is not significant & parameter names are irrelevant. ex 1: int square(int x) { return x * x; } ex 2: 1: 2: 3: 4: double square (double y) {return y * y; } void main() { integer = 7; double dbl = 7. 5; cout << square(integer); // int square(int x) cout << square(dbl); // double square(double x) } int foo(int, int); int foo(int); char foo(int, int); int foo(const int); 1/15/2022 August 13, 1998 //okay //conflict with 1 //conflict with 2 bi@cs. uofs. edu 22

Summary of Module 1 z C++ single-line comments z C++ stream I/O z Declarations of variables z Inline functions z Reference parameters z The const qualifier z The new and delete operators z Default arguments z Scope operator z Function overloading 1/15/2022 August 13, 1998 bi@cs. uofs. edu 23

Programming Assignments z Get Started with VC++’s IDE y Design a C++ program that prints “Hello World!”. Use VC++ 5. 0 to edit, compile, and run your program. See next slide for instructions z Improve Example 3 y The push and pop operations in the example do not check whether the stack is full or empty. Type in the program and change the two operations into the following, respectively: bool Push(int item); // return true if successful, return false otherwise bool Pop(int& item); // return true if successful, return false otherwise // Note: item is passed-by-reference. y Modify the main function accordingly. 1/15/2022 August 13, 1998 bi@cs. uofs. edu 24

Compiling C++ Programs Using VC++ This is an extremely simple guide on how to compile a C++ program using Microsoft Visual C++ 5 Begin Here: 1. 2. 3. 4. 5. 6. 7. 8. Start-up Microsoft Visual C++ 5. 0 (Start -> Programs -> Microsoft Visual C++ 5. 0) (File -> New) prompts new project window. Select the type of project you will be working on (e. g. Win 32 Console Application). Change the directory to the desired directory and type in a unique project name You should be in the project window. Located on left side is the navigation bar. The tabs at the bottom take you to: ·The Class View - Lists the classes contained in your code ·File View - Lists the files containing the code ·Info View - An online help section To add a file in the project, select tag "File View" in the navigation bar. Select the project name, and click new file (File -> New). Select type of file you are adding to your project. (e. g. C++ Source Code). You must type in the name of the file, but unlike UNIX, filenames can be anything here (the extension. cpp will be added automatically to the file) A new document window will appear where the code can be entered. ENTER CODE NOW! Once code input is ready, Code must be compiled (BUILD -> BUILD) or simply press F 7 The debug window will appear along the bottom of the screen. It gives the current status of the compilation and linking process. Once it is done, it will report any errors in the core. If there were errors: 1. 2. 3. 4. Any errors during compilation or linking will be displayed in the debug window at the bottom of the screen Double clicking on any error will place a pointer in the appropriate line of code in the document window. Fix errors and compile again (Build - Compile) or press <control> F 7 If no errors remain, proceed to next section. Else repeat from step number one in this section If there were no errors: 1. 2. Program is ready for execution. BUILD -> EXECUTE to run the program. (or press <control> F 5) The program will pop-up in a console window (or other depending on your choice of project) DONE! This manual is downloaded from http: //www. aul. fiu. edu/tech/compile. html with limited modification. 1/15/2022 August 13, 1998 bi@cs. uofs. edu 25