Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D....

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 [email protected]

Transcript of Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D....

Page 1: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Introduction to C++ ProgrammingModule 1

An Overview of C++ and OO Programming

Yaodong Bi, Ph.D.Department of Computing Sciences

University of Scranton(717)[email protected]

Page 2: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Outline

Module 1 - An Overview of C++ and OO Programming

Module 2 - Classes and Operator Overloading

Module 3 - Inheritance and Dynamic Binding

Module 4 - Function and Class Templates

Module 5 - C++ Stream I/O and Exception Handling

Page 3: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

History

Developed by Bjarne Stroustrup at AT&T, 1986. Originally called “C++ with classes” C++: Enhanced version of C.

Stronger type checking Support for data abstraction Support for OO programming Support for Generic programming

C++ is a superset of C. ISO/ANSI C++ Standard, 1998

Page 4: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Example 1: A Simple C++ Program// Convert miles to kilometers#include <iostream.h>

const double m_to_k = 1.609;inline double convert(double mi)

{ return (mi *m_to_k);}

int main(){

double miles;cout << "Input distance in miles: ";cin >> miles;cout<<"\nDistance: "<< convert(miles)

<< " km." << endl;return 0;

}

New Comment Style // Convert ...

iostream.h file C++ stream I/O

Keyword const constant variable

Keyword inline inline code if possible

Input/output cin >> and cout <<

Stream manipulator endl (end line) = “\n”

Page 5: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Example 2: Reference Parameters andFunction Overloading

//function.cpp#include <iostream.h>

void square(int*); //by pointervoid sqrByRef(int&); //by

referencevoid sqrByRef(double&); //overloaded

int main(){

int num = 3;square(&num); //square(int*)cout <<"by pointer (int*): " << num << endl;int rNum =4;sqrByRef(rNum); //sqrByRef(int&)

cout <<"by reference (int): " << rNum << endl;double dbl = 3.5;sqrByRef(dbl); //sqrByRef(double&)cout <<"by reference (double): "

<< dbl << endl;return 0;

} // end of main

void square(int* sqr){ *sqr = (*sqr) * (*sqr); }

void sqrByRef(int& sqr){ sqr = sqr * sqr; }

void sqrByRef(double& y) { y = y*y; }

Page 6: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Example 2: function -- Cont’d

Function declaration A function must be

declared before it is used. void square(int*); // prototype

Pass by reference A reference is a alias of

the variable.sqr in sqrByRef(int&) isan alias for rNum in main()

Variable declaration A variable may be

declared when it is used.int rNum;

Function overloading several functions have

the same namevoid sqrBtRef(int&); andvoid sqrByRef(double&);

distinguished with different parameter lists.

int& for the first anddouble& for the second

Compiler finds the right one

Page 7: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Example 3: A Stack Class//Class Specification// Stack.hconst int maxSize = 10;

class CStack {public: // public interface

CStack(int sz = maxSize); // constructorvoid Push (int item);int Pop();bool IsEmpty() const;bool IsFull() const;~CStack(); // Destructor

private: // private implementationint* m_Array;int m_nTop;int m_nSize;

};

//Class Implmentation// stack.cpp#include <iostream.h>#include "Stack.h"

CStack:: // class scope oepratorCStack(int sz) {

m_Array = new int[sz];m_nSize = sz;m_nTop = -1;

}

CStack::~CStack(){

delete [] m_Array;}

Page 8: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Example 3: Stack - cont’d// stack.cpp - continued

void CStack::Push(int item) {

m_Array[++m_nTop] = item;}int CStack::Pop() {

return m_Array[m_nTop--];}bool CStack::IsEmpty() const{

return (m_nTop < 0);}bool CStack::IsFull() const{

return (m_nTop == m_nSize - 1);}

// class.cpp

#include <iostream.h>#include "Stack.h"

void main(){

CStack stack;

for ( int i = 1; i < maxSize+3; i++){

if (!stack.IsFull()) stack.Push(i*100);}while (!stack.IsEmpty()){

cout << stack.Pop() << endl;}

}

Page 9: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Example 3: Stack - cont’d

Information Hiding public interface and private implementation-

When the private implementation is changed, the users of the class do not need to change.

Constructor: It is executed when an object of the class is

created. Initialize the object

Destructor: It is executed when an object of the class is

destroyed. Clean up

Page 10: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Example 4: Class and Function Templates// stackTmpl.h

const int maxSize = 10;

template <class T> class CStack {public: // public interface

CStack(int sz = maxSize);void Push (const T& item);T Pop();bool IsEmpty() const;bool IsFull() const;~CStack();

private: // private implementationT* m_Array;int m_nTop;int m_nSize;

};

// stack.cpp

#include <iostream.h>#include "stackTmpl.h"

template<class T> CStack<T>::CStack(int sz) {

m_Array = new T[sz];m_nSize = sz;m_nTop = -1;

};template<class T> void CStack<T>::Push(const T& item) {

m_Array[++m_nTop] = item;};template<class T> T CStack<T>::Pop() {

return m_Array[m_nTop--];};

Page 11: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Example 4: Templates -- cont’d// stackTmpl.cpp -- cont’dtemplate<class T> bool CStack<T>::IsEmpty() const{

return (m_nTop < 0);};template<class T> bool CStack<T>::IsFull() const{

return (m_nTop == m_nSize - 1);};template<class T> CStack<T>::~CStack(){

delete [] m_Array;};

// template.cpp ---- Main function

#include <iostream.h>#include "stackTmpl.cpp"

template <class T> void Print(CStack<T>& stack);

void main(){

CStack<int> istack;CStack<char> cstack;

for ( char i = ’A'; i < ’A'+10; i++){

if (!istack.IsFull()) istack.Push(int(i));

if (!cstack.IsFull()) cstack.Push(i);

}Print(istack);Print(cstack);

}

template<class T> void Print(CStack<T>& stack){

while (!stack.IsEmpty()){

cout << stack.Pop() << endl;}

}

Page 12: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Example 4: Templates -- cont’d

Class Templates Template definition

template <class T> class CStack

{ public: CStack(int sz = maxSize);

void Push (const T& item);...private:

T* m_Array;… };

Template instantiation// stack of integerCStack<int> iStack; // stack of doubleCStack<double> dStack; // stack of charCStack<char> cStack;

Function Templates Template definition

template<class T> void Print(CStack<T>&

stack){ while (!stack.IsEmpty()) { cout << stack.Pop() <<

endl;}

} Template instantiation

// stack of integerCStack<int> iStack; // stack of doubleCStack<double> dStack; // stack of charCStack<char> cStack;

Page 13: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Example 5: Inheritance and Dynamic Binding

CPersonm_name : stringm_age : int

GetName() costGetAge() constSetName(string)SetAge(int)Print() const

CManagerm_nMgrLevel : int

GetMgrLevel() constSetMgrLevel(int mgrLevel)Print() const

CEngineerm_nEngType : int

GetEngType() constSetEngType(int engType)Print() const

CPerson Parent class

CManager & CEngineer Child classes “is-a” CPerson Inherit all the operations

and attributes of CPerson

Print() virtual function Redefined in child

classes Dynamic binding

Page 14: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Example 5: Inheritance//person.h

#ifndef PERSON_H#define PERSON_H

#include <string>

using namespace std;

class CPerson {public:

CPerson(const string name, int age = 30);~CPerson();string GetName() const;int GetAge() const;void SetName(string);void SetAge(int);virtual void Print() const;

private:string m_name;int m_age;

};

#endif

//person.cpp#include <iostream>#include "person.h"using namespace std;

CPerson::CPerson(string name, int age):m_name(name), m_age(age)

{ }CPerson::~CPerson(){ }string CPerson::GetName() const{

return m_name;}int CPerson::GetAge() const{

return m_age;}void CPerson::SetName(string name){

m_name = name;}void CPerson::SetAge(int age){

m_age = age;}void CPerson::Print() const{

cout << "Name:\t\t" << m_name << endl;cout << "Age:\t\t" << m_age << endl;

}

Page 15: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Example 5: Inheritance -- cont’d//manager.h

#ifndef MANAGER_H#define MANAGER_H

#include "person.h"

class CManager: public CPerson{public:

CManager(string name, int age=25, int mgrLevel=1);

~CManager();int GetMgrLevel() const;void SetMgrLevel(int level);virtual void Print() const;

private:int m_nMgrLevel;

};

#endif

//manager.cpp

#include <iostream>#include "manager.h"

CManager::CManager(string name, int age, int mgrLevel):CPerson(name, age)

{m_nMgrLevel = mgrLevel;

}CManager::~CManager(){}int CManager::GetMgrLevel() const{

return m_nMgrLevel;}void CManager::SetMgrLevel(int level){

m_nMgrLevel = level;}void CManager::Print() const{

CPerson::Print();cout << "Mngmnt Level:\t" << m_nMgrLevel

<< endl;}

Page 16: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Example 5: Inheritance -- cont’d//engineer.h

#ifndef ENGINEER_H#define ENGINEER_H

#include "person.h"

class CEngineer: public CPerson{public:

CEngineer(string name, int age=25, int engType = 1);

~CEngineer();int GetEngType() const;void SetEngType(int engType);virtual void Print() const;

private:int m_nEngType;

};

#endif

//engineer.cpp

#include <iostream>#include "engineer.h"

using namespace std;

CEngineer::CEngineer(string name, int age, int engType)

:CPerson(name, age), m_nEngType(engType){}CEngineer::~CEngineer(){}int CEngineer::GetEngType() const{

return m_nEngType;}void CEngineer::SetEngType(int engType){

m_nEngType = engType;}void CEngineer::Print() const{

CPerson::Print();cout << "Eng Type:\t" << m_nEngType << endl;

}

Page 17: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Example 5: Inheritance -- cont’d//inheritance.cpp

#include <iostream>#include "manager.h"#include "engineer.h"

int main(){

CManager mngr1("Bi"); //default values CManager mngr2("Brown", 25, 20);CEngineer engineer("Smith", 20, 15);

// call an inherited functionmngr1.SetName("Johnson");

CPerson* array[3];array[0] = &mngr1;array[1] = &engineer;array[2] = &mngr2;

// inheritance.cpp -- cont’d

for (int i=0; i<3; i++){

array[i]->Print();cout << endl;

}return 0;

}

Page 18: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

1. C++ as a better C C++ single-line comments

A common programming error is forgetting to close a c-style comment with “*/”. Using // can avoid that.

C++ stream I/O #include <iostream.h> cin>> for input and cout<< for output less error prone

Declarations of variables Don’t declare a variable until it can be initialized. Introduce the variable into the smallest scope possible.

Inline functions Prefer inline over #define Ex: inline int square(int); should only be used for simple, small functions. Reduce execution time, but increase program size.

Page 19: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

1. C++ as a better C Reference parameters

A reference is an alias for the variable it references to. A reference must be initialized

ex: int count;int& rCount = count;rCount = 100; // count = rCount = 100

Use const reference parameters for large objects.ex: void fooByRef(const Type& r);

void fooByVal(const Type r);....Type y;fooByRef(y);//in fooByRef, r is a reference to y and// r cannot be modified in fooByVal.fooByVal(y)//in fooByVal(), 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.

Page 20: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

1. C++ as a better C The const qualifier

Prefer const over #define - const variables are visible to debuggers.

const int MaxSize = 20;const char* ptr; // a pointer pointing to a const charchar* const roPtr // a const pointer to a char

The new and delete operatorsIn C In C++Type* ptr = malloc(sizeof(Type)); Type* ptr = new Type;free(ptr); delete ptr;Ex: ...

int* ptr1 = new int(200); // *ptr = 200int* ptr2 = new int[200]; // ptr is an array with 200 elements.delete ptr1; // delete a single objectdelete [] ptr2; // delete an arrayCStack* pStack = new CStack; // a new stackdelete pStack; //delete stack - ~CStack called

Page 21: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

1. C++ as a better C Default arguments

provide a value for a argumentint foo(int x, int y=10);...

int z = foo(20); // equal to foo(20,10);int w = foo(30, 20); // the passed overwrites the default

Default arguments must the rightmost arguments in the list.

Scope operator 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; // global int value is not visiblecout << value; // print local value (double) - 1.234;cout << ::value; // print global value (int) - 100...

Page 22: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

1. C++ as a better C Function overloading

several functions have the same name with different signatures.

The signature of a function is: parameter list

Return type is not significant & parameter names are irrelevant.

ex1: int square(int x) { return x * x; } double square (double y) {return y * y; } void main() {

int integer = 7;double dbl = 7.5;cout << square(integer); // int square(int x)cout << square(dbl); // double square(double x)

}ex2:

1: int foo(int, int); //okay2: int foo(int); //okay3: char foo(int, int); //conflict with 14: int foo(const int); //conflict with 2

Page 23: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Summary of Module 1

C++ single-line comments C++ stream I/O Declarations of variables Inline functions Reference parameters The const qualifier The new and delete operators Default arguments Scope operator Function overloading

Page 24: Introduction to C++ Programming Module 1 An Overview of C++ and OO Programming Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.

Programming Assignments

Get Started with VC++’s IDE Design a C++ program that prints “Hello World!”. Use VC+

+ 5.0 to edit, compile, and run your program. See next slide for instructions

Improve Example 3 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.

Modify the main function accordingly.

Page 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.

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. Start-up Microsoft Visual C++ 5.0 (Start -> Programs -> Microsoft Visual C++ 5.0 -> Microsoft Visual C++ 5.0) 2. (File -> New) prompts new project window. Select the type of project you will be working on (e.g. Win32 Console

Application). Change the directory to the desired directory and type in a unique project name 3. 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

4. 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).

5. 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)

6. A new document window will appear where the code can be entered. ENTER CODE NOW! 7. Once code input is ready, Code must be compiled (BUILD -> BUILD) or simply press F7 8. 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. Any errors during compilation or linking will be displayed in the debug window at the bottom of the screen 2. Double clicking on any error will place a pointer in the appropriate line of code in the document window. 3. Fix errors and compile again (Build - Compile) or press <control> F7 4. If no errors remain, proceed to next section. Else repeat from step number one in this section

If there were no errors: 1. Program is ready for execution. BUILD -> EXECUTE to run the program. (or press <control> F5) 2. 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.