C++ Yeting Ge.

Slides:



Advertisements
Similar presentations
Lecture Computer Science I - Martin Hardwick The Programming Process rUse an editor to create a program file (source file). l contains the text of.
Advertisements

Programming Languages and Paradigms
Programming Languages and Paradigms The C Programming Language.
Derived Classes. C++ 2 Outline  Definition  Virtual functions  Virtual base classes  Abstract classes. Pure virtual functions.
C/c++ 4 Yeting Ge.
Written by: Dr. JJ Shepherd
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Java Syntax Primitive data types Operators Control statements.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
C++ Training Datascope Lawrence D’Antonio Lecture 1 Quiz 1.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Review of C++ Programming Part II Sheng-Fang Huang.
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
COMPUTER PROGRAMMING. Data Types “Hello world” program Does it do a useful work? Writing several lines of code. Compiling the program. Executing the program.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Programming Language C++ Xulong Peng CSC415 Programming Languages.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Pointer and Array Lists Chapter 3, Summary CS 244 Brent M. Dingle, Ph.D. Game Design and Development Program Department of Mathematics, Statistics, and.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
COMPUTER PROGRAMMING. variable What is variable? a portion of memory to store a determined value. Each variable needs an identifier that distinguishes.
C/C++ 3 Yeting Ge. Static variables Static variables is stored in the static storage. Static variable will be initialized once. 29.cpp 21.cpp.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
1.Which of the following statements is correct?
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
C LANGUAGE Characteristics of C · Small size
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
C Part 1 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens A History Lesson Development of language by Dennis Ritchie at Bell.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
C++ Lesson 1.
Asst.Prof.Dr. Tayfun ÖZGÜR
C ++ MULTIPLE CHOICE QUESTION
Dynamic Storage Allocation
Introduction to Computers Computer Generations
Data types Data types Basic types
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ INTERVIEW QUESTIONS
Andy Wang Object Oriented Programming in C++ COP 3330
Programming Languages and Paradigms
Programming Paradigms
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes
Chap 2. Identifiers, Keywords, and Types
Programming Languages and Paradigms
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Presentation transcript:

C++ Yeting Ge

Outline Fundamentals of C++ Class & inheritance Overloading & overriding Templates, Error handling,…

Reference C/C++ The C Programming Language Brian Kernighan & Denis Ritchie The C++ Programming Language Bjarne Stroustrup

An example #include<iostream.h> int main() { int i=0; double x=2.3; char s[]="Hello"; cout<<i<<endl; cout<<x<<endl; cout<<s<<endl; return 0; } 1.cpp

Lexical elements Identifiers: case sensitive Reservered words nCount, strName, Strname Reservered words if, else, while Operators +, ==, &, &&, ‘? :’ Preprocessor Directives #include, #if,

Primitive Data Types Name Description Range char 1 short 2 long 4 int Size (bytes) Description Range char 1 character or eight bit integer signed: -128..127 unsigned: 0..255 short 2 sixteen bit integer signed: -32768..32767 unsigned: 0..65535 long 4 thirty-two bit integer signed: -231 .. 231-1 unsigned: 0 .. 232 int * (4) system dependent, likely four bytes or thirty-two bits float floating point number 3.4e +/- 38 (7 digits) double 8 double precision floating point 1.7e +/- 308 (15 digits) long double 10 long double precision floating point 1.2e +/- 4932 (19 digits) bool boolean value false → 0, true → 1 {0,1}

Variables declaration & assignments #include<iostream> using namespace std; int main() { int i,j,k; int l; i=10; j=k=l=20; //j=(k=(i=20)) cout<<"i="<<i<<endl; cout<<"k="<<k<<endl; cout<<"l="<<l<<endl; i+=10; //i = i + 10; i++; //i = i + 1; cout << "i="<<i<<endl; } 2.cpp

Expressions Boolean expressions Arithmetic expression Assignment ? : == , != , >, >=, < , <=, … && , || … Arithmetic expression + , - , *, / ,% … &, | … Assignment = ? : Expressions have values

Example of expressions 7 && 8 7 & 8 7 / 8 7 % 8 7 >> 1 (i > 127 ? true : false) (i > 127 ? i-127 : i) 3.cpp 4.cpp

Statements Assignments Conditional Loop Goto,break,continue Compound statement

Conditional if A B ; if A B else C If ( I > 10) {cout<<“ > 10”;} else {cout<<“ < 10”;} 5.cpp

Trick What is the difference? If (i==1) …… If (i=1)…… A better way to compare a variable with a constant if (constant==variable).. if (10 == i)…..

Trick If (i) …… If (1) …….

Loop, for for (A;B;C) D 1 execute A 2 execute B 3 if the value of B is false(==0), exit to D 4 execute C, goto 2 for(i=0; i<n; i++){cout << A[i]<<endl;} for(;;) {…}

Loop, while & do while while A B do A while B While (i>10) { x-=4;i--;} do A while B do {x -=4;i--} while (i>10);

Goto,break,continue For (; ;){ … If (a==b) break; } C ----------------------------------------- For (;;){ {B} If (a==b) continue; {A}

switch switch (grade){ case ‘A’:++nACount;break; case ‘B’:++nBCount;break; case ‘C’:++nCCount;break; case ‘D’:++nDCount;break; default: cout<<“Something wrong\n”;break; } Try: write a program using the code segment. Then remove several of the ‘break’s and see the difference

Scoping

functions Can not define a function within another function* Parameters passed by value or reference

Example #include<iostream> using namespace std; int square (int); int main () { int z = 4; cout << square(z); } int square (int x) { x = (x*x); return x; } 6.cpp

Pass by value void swap1(int x,int y) { int temp=x; x = y; y=temp; }

Pass by reference void swap2(int& x,int& y) { int temp=x; x = y; y=temp; } 7.cpp

Array in C/C++ Definition No bounds checking Int a[10]; //int[10] a; Char b[12]; No bounds checking The cause of many problems in C/C++

Array Int x[7]; Int score[3][3]={{1,2,3},{2,3,4}{3,5,6}};

Array: confusing What is the result of the program. So, array is passed by reference? 8.cpp

Pointer Example The value of a pointer is just an address. int *p, char * s; The value of a pointer is just an address. Why pointers? Dereferencing (*) Get the content Referencing (&) Get the address of

Examples of pointer int *p; Int a; a=10; p=&a; *p=7; Int b=*p; You must initialize a pointer before you use it 81.cpp 82.cpp

Array and pointer 9.cpp

arithmetic of pointer Suppose n is an integer and p1 and p2 are pointers p1+n p1-n p1-p2 91.cpp

Strings C C++ library: string class A string is an array of chars end with ‘\0’ char name[]=“ABC”; char school_name[]={‘N’,’Y’,’U}; C++ library: string class 10.cpp 101.cpp

Dynamic allocating memory new , delete int *p=new int; int *p=new int [12]; delete p; delete []p; malloc,… 11.cpp (difference between different implementations)

Outline Fundamentals of C++ Class & inheritance Overloading & overriding Templates, Error handling,…

Struct: struct person { long nId; char strName[30]; int nAge; float fSalary; char strAddress[100]; char strPhone[20]; }; struct person a , b, c; struct person *p; 12.cpp

union union num { int x; float y; } 13.cpp

More in a stucture: operations struct box { double dLength,dWidth,dHeight; double dVolume; double get_vol() return dLength * dWidth * dHeight; } } 14.cpp 141.cpp

Class class box { double dLength,dWidth,dHeight; double dVolume; public: double vol(){return dLength * dWidth * dHeight;} } 15.cpp

Public vs. private Public functions and variables are accessible from anywhere the object is visible Private functions and variable are only accessible from the members of the same class and “friend” Protected

class class box { double dLength,dWidth,dHeight; double dVolume; public: double vol() ; } dbouble box::vol() return dLength * dWidth * dHeight;} } 16.cpp

Constructors A special member function with the same name of the class No return type (not void) Executed when an instance of the class is the created 17.cpp

Deconstructors A special member function with no parameters Executed when the class is destroyed 18.cpp

Tricky What is the result of the program 19.cpp How many times the constructor executed? How many times the deconstructor executed Examples 20.cpp 21.cpp

Empty constructor & Copy constructor The default constuctor with no parameters when an object is created Do nothing: e.g. Examp::Examp(){} Copy constructor Copy an object (shallow copy) The default consturctor when an object is copied (call by value, return an object, initialized to be the copy of another object) 22.cpp {try not to pass an object by value)

Inheritance Base class Derived class 23.cpp Protected members 24.cpp

Having same name? Use the function/variable in the current class 27.cpp

Constructors 28.cpp

Inheritance base derived Public inheritance public protected private N/A Private inheritance Protected inheritance

Static members in class Static variables Shared by all objects Static functions Have access to static members only Static members can be accessed by the class name 29.cpp 21.cpp

Friend functions Have access to the private members of a class. Must be declared as friend in that class. Why friend functions? efficiency 30.cpp 31.cpp 32.cpp

Friend class A class can be declared as the friend of another class.

Outline Fundamentals of C++ Class & inheritance Overloading & overriding Templates, Error handling,…

Function overloading Define several functions of the same name, differ by parameters. void Show() void Show(char *str) Void show(int x) 33.cpp

Function overloading Must have different parameters Static binding int func1(int a, int b); double func1(int a, int b); void func(int value); void func(int &value); Static binding The compilers determine which function is called. (Often used for the multiple constructors)

Operator overloading Define new operations for operators (enable them to work with class objects). + - * / = < > += -= *= /= << >> <<= >>= == != <= >= ++ -- % & ^ ! | ~ &= ^= |= && || %= [] () new delete Class date x ,y X+y x-y x>y, x&y

Special member functions Ret_type class_name::operator<>(arg_list) 34.cpp

Overloading = this pointer 35.cpp = & copy constructor

Operator overloading by friend functions Sometimes it is more convenient to use friend functions to overload a binary operator 36.cpp 37.cpp

Overloading examples () ++ 37-1.cpp 37-2.cpp 37-3.cpp 37-4.cpp

Overloading summary Same name Different parameters Static binding (compile time) Anywhere

Type conversion between classes An object of derived class is an object of the base class. A pointer of the base class can be assigned to an address of the derived class. 38.cpp

Redefine It is possible to redefine a member of the base class in the derived class Rule of scoping 40.cpp

What is the result? 41.cpp The way out 43.cpp

Virtual function & overriding Define a member function to be virtual Use pointer/reference/member functions to call virtual functions Dynamic binding Time consuming The constructor cannot be virtual Must be a member function

Virtual functions examples By pointers 42.cpp By reference 43.cpp By member function of the base class 44.cpp

Overloading & overriding Polymorphism Static and dynamic Compile time and running time Parameters Anywhere / between the base and derived class

Pure virtual functions & abstract class A function declared without definition virtual ret_type func_name(arg_list)= 0; Abstract class A class contains one or more pure functions Can not be instantiated Can be used to define pointers

Outline Fundamentals of C++ Class & inheritance Overloading & overriding Templates, Error handling,…

Function Templates Generic function for different types. E.g. get the min value of three variables (int, float, char…) Define function templates 46.cpp Template<class S, class T…> func_name(…) Func_name<type name>(…) something like macro More powerful than macro

Using template functions Func_name<type_name list>(…) 47.cpp Generic quick sort 47-1.cpp

Class templates Generic classes Define class templates 48.cpp Template<class T> Class {…} Template<class T> ret_type class_name<type_name> :: func_name ( … ){ } 48.cpp

Class template examples Class_name<type_name..> obj… Array class 49.cpp Linked list 50.cpp

overload template functions It is possible to overload a template function. 51.cpp

Template specialization An example from www.cplusplus.com 52.cpp template <> class class_name <type>

Template value parameters Template can have parameters other than type names 53.cpp

Default value for templates paramters template <class T = char> // With a default value. template <int Tfunc (int)> // A function as parameter. the implementation (definition) of a template class or function must be in the same file as the declaration.

Execptions try { // code to be tried throw exception; } catch (type  exception) { // code to be executed in case of exception }

Examples of exception 54.cpp throw out an object. 55.cpp

Uncaught exception Uncaught exceptions will be thrown into outer scope. If no catch, usually program will terminate. Void terminate();

I/O system iostream.h cin,cout,cerr,clog iostream,fstream,strstream Flags 57.cpp 58.cpp Overload “<<“ 59.cpp 60.cpp 61.cpp 62.cpp 63.cpp 64.cpp