C++ Basics & OOP 2019/3/14 History of C++ Developed by Bjarne - - PowerPoint PPT Presentation

c basics oop
SMART_READER_LITE
LIVE PREVIEW

C++ Basics & OOP 2019/3/14 History of C++ Developed by Bjarne - - PowerPoint PPT Presentation

Poly- mor- phism Abstra ction Class OOP Inheri -tance En- capsu- lation Kuan-Ting Lai C++ Basics & OOP 2019/3/14 History of C++ Developed by Bjarne Stroustrup starting in 1979 at Bell Labs Originally named C with Classes


slide-1
SLIDE 1

C++ Basics & OOP

Kuan-Ting Lai 2019/3/14

OOP

Class Abstra ction Inheri

  • tance

En- capsu- lation Poly- mor- phism

slide-2
SLIDE 2

History of C++

  • Developed by Bjarne Stroustrup

starting in 1979 at Bell Labs

  • Originally named C with Classes

but renamed C++ in 1983

  • C++ is a statically typed, compiled,

general-purpose, case-sensitive, free-form programming language

slide-3
SLIDE 3

C++ Hello World

  • Compile and Run on

Linux

$ g++ hello.cpp $ ./a.out Hello World /* This is Your First C Program: Hello World */ #include <iostream> using namespace std; // main() is where program execution begins. int main() { cout << "Hello World"; // prints Hello World return 0; }

slide-4
SLIDE 4

Semicolons and Blocks in C++

  • Use semincolon ; as a statement terminator
  • Blocks { }

x = y; y = y + 1; add(x, y); { cout << "Hello World"; return 0; }

slide-5
SLIDE 5

C++ Keywords

asm else new this auto enum

  • perator

throw bool explicit private TRUE break export protected try case extern public typedef catch FALSE register typeid char float reinterpret_ cast typename class for return union const friend short unsigned const_cast goto signed using continue if sizeof virtual default inline static void delete int static_cast volatile do long struct wchar_t double mutable switch while dynamic_cast namespace template

slide-6
SLIDE 6

C++ Data Types

Type Keyword Boolean bool Character char Integer int Floating point float Double floating point double Valueless void Wide character wchar_t

slide-7
SLIDE 7

C++ Modifiers

  • Data Type modifiers

− signed − unsigned − long − short

  • Type qualifiers

− Const − volatile − restrict

slide-8
SLIDE 8

Data Range

Type Typical Bit Width Typical Range char 1byte

  • 128 to 127 or 0 to 255

unsigned char 1byte 0 to 255 int 4bytes

  • 2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295 short int 2bytes

  • 32768 to 32767

unsigned short int 2bytes 0 to 65,535 long int 8bytes

  • 2,147,483,648 to 2,147,483,647

unsigned long int 8bytes 0 to 4,294,967,295 long long int 8bytes

  • (2^63) to (2^63)-1

unsigned long long int 8bytes 0 to 18,446,744,073,709,551,615 float 4bytes double 8bytes long double 12bytes wchar_t 2 or 4 bytes 1 wide character

INT_MAX Overflow

slide-9
SLIDE 9

Enumerated Types

  • enum enum-name { list of names } var-list;

#include <stdio.h> enum SHAPE { CIRCLE, RECT = 3, TRIANGLE }; int main() { SHAPE sp = RECT; printf("%d\n", sp); sp = TRIANGLE; printf("%d\n", sp); sp = CIRCLE; printf("%d\n", sp); return 0; }

slide-10
SLIDE 10

Variable Scope

#include <iostream> using namespace std; // Global variable declaration: int g; int main() { // Local variable declaration: int a, b; // actual initialization a = 10; b = 20; g = a + b; cout << g; return 0; }

slide-11
SLIDE 11

Literals

/* Integer Literals */ 212 // Legal 215u // Legal 0xFeeL // Legal 078 // Illegal: 8 is not an octal digit 032UU // Illegal: cannot repeat a suffix /* Floating point literals */ 3.14159 // Legal 314159E-5L // Legal 510E // Illegal: incomplete exponent 210f // Illegal: no decimal or exponent .e55 // Illegal: missing integer or fraction

slide-12
SLIDE 12

Decision Making

Condition Conditional Code True False // if ... else ... if (score > 90) { grade = 'A'; } else if (score > 80) { grade = 'B'; } else grade = 'F'; // Switch case switch (grade) { case 'A': printf('Great!\n'); break; case 'B': printf('OK!\n’); break; case 'C': printf('Work harder!\n’); break; default: printf('Game over\n’); break; }

slide-13
SLIDE 13

C++ Loop

// 1. for Loop, sum = 1 + 2 + … + 10 sum = 0; for (int i = 1; i <= 10; i++) sum += i; // 2. while Loop sum = 0; i = 1; while(i <= 10) { sum += i++; } // 3. do { ...} while (...); sum = 0; i = 1; do { sum += i++; } while (i <= 10); Condition Conditional Code True False

slide-14
SLIDE 14

C++ Functions

  • Declaration tells the compiler about a function's name, return type,

and parameters

  • Definition provides the actual body of the function.

return_type function_name(parameter list) { ... (code) ... }

slide-15
SLIDE 15

Max Function Example

#include <iostream> using namespace std; // function declaration int max(int num1, int num2); int main() { // local variable declaration: int a = 100; int b = 200; cout << "Max value is : " << max(a, b) << endl; return 0; } // function returning the max between two numbers int max(int num1, int num2) { // local variable declaration int result; (num1 > num2) ? result = num1 : result = num2; return result; }

slide-16
SLIDE 16

Function Arguments

  • Call by Value
  • Call by Pointer
  • Call by Reference

#include <iostream> using namespace std; // Call by Pointer void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } // Call by Reference void swap(int &a, int &b) { int temp = a; a = b; b = temp; } int main() { int a = 5, b = 23; swap(&a, &b); // Call by Pointer cout << "a = " << a << ", b = " << b << endl; swap(a, b); // Call by Reference cout << "a = " << a << ", b = " << b << endl; return 0; }

slide-17
SLIDE 17

C++ Arrays

  • Initialize an array
  • Access elements

double balance[] = { 1000.0, 2.0, 3.4, 17.0, 50.0 };

float val[10]; // Initialize an array for (int i = 0; i < 10; i++) val[i] = (float)i; // Multi-dimensional array unsigned char img[256][256];

slide-18
SLIDE 18

C++ new & delete

  • Dynamic memory is allocated

during runtime

int *pData; pData = new int[10000]; //... // Do something using pData //... delete[] pData;

slide-19
SLIDE 19

C-Style Character String

  • 1D character array terminated by a null character '\0'

int main() { char hello[6] = { 'H', 'e', 'l', 'l', 'o', '\0' }; char world[] = "World"; cout << hello << " " << world; return 0; }

slide-20
SLIDE 20

C++ Pointers

  • Pointer is a variable which saves the memory address of another variable

− type *var-name;

int main() { int var = 20; // actual variable declaration. int *p_var; // pointer variable p_var = &var; // store address of var in pointer variable cout << "Value of var variable: "; cout << var << endl; // print the address stored in ip pointer variable cout << "Address stored in p_var variable: "; cout << p_var << endl; // access the value at the address available in pointer cout << "Value of *p_var variable: "; cout << *p_var << endl; return 0; }

slide-21
SLIDE 21

C++ Reference

  • Reference is an alias of an existing variable

− Cannot be NULL − Cannot be changed after initalized

int main() { // declare simple variables int i; // declare reference variables int &r = i; i = 5; cout << "Value of i : " << i << endl; cout << "Value of i reference : " << r << endl; return 0; }

slide-22
SLIDE 22

C++ Class

  • Define a Box class with length, width, height

class Box { public: double length; // Length of a box double width; // Width of a box double height; // Height of a box };

  • Create instances

Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box

slide-23
SLIDE 23

C++ Encapsulation

  • Access control modifiers

− public, private, protected

#include <iostream> #include <vector> #include <string> using namespace std; class Box { public: double length; // Length of a box double width; // Width of a box double height; // Height of a box protected: vector<string> barcodes; private: char owner_name[64]; };

slide-24
SLIDE 24

C++ Inheritance (2-1)

  • Syntax

− class derived_class : public base_class

  • Declare a base class “Shape”

− Data: width, height − Functions: setWidth, setHeight

  • Declare a derived class

“Rectangle”

#ifndef _SHAPES_H_ #define _SHAPES_H_ // Base class class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; // Derived class class Rectangle : public Shape { public: int area() { return (width * height); } }; #endif

shapes.h

slide-25
SLIDE 25

C++ Inheritance (2-2)

  • Create a instance of Rectangle

− Rectangle Rect;

  • Call the functions of base class to

set width & height

− Rect.setWidth(5); − Rect.setHeight(7);

  • Call the function of derived class

− Rect.area()

#include <iostream> using namespace std; #include “shapes.h” int main() { Rectangle Rect; Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. cout << "Total area: " << Rect.area(); cout << endl; return 0; }

main.cpp

slide-26
SLIDE 26

C++ Abstraction

  • Force derived classes to implement a specific function
  • A virtual function “= 0” is a pure virtual function
  • In C++, pure virtual function is also called interface

// Base class class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } virtual float area() = 0; protected: int width; int height; };

slide-27
SLIDE 27

C++ Polymorphism (2-1)

  • Overriding area()

class Rectangle : public Shape { public: Rectangle(int a = 0, int b = 0) :Shape(a, b) { } float area() { cout << "Rectangle class area :" << endl; return (width * height); } }; class Triangle : public Shape { public: Triangle(int a = 0, int b = 0) :Shape(a, b) { } float area() { cout << "Triangle class area :" << endl; return (width * height / 2); } };

slide-28
SLIDE 28

C++ Polymorphism (2-2)

  • Create a base class pointer

− Shape *shape;

  • Create instances of derived

classes

− Rectangle rec(10, 7); − Triangle tri(10, 5);

  • Get reference of instance

− shape = &rec;

  • Print result

− shape->area();

#include <iostream> using namespace std; #include “shapes.h” int main() { Shape *shape; Rectangle rec(10, 7); Triangle tri(10, 5); // store the address of Rectangle shape = &rec; // call rectangle area. shape->area(); // store the address of Triangle shape = &tri; // call triangle area. shape->area(); return 0; }

slide-29
SLIDE 29

Constructor & Destructor

  • Constructor

− Called when an object is created − Initialize data

  • Destructor

− Called when an object is deleted − Can be used to clean data

// Base class class Shape { public: Shape(int a=0, int b=0) { width = a; height = b; } ~Shape(){} void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } virtual float area() = 0; protected: int width; int height; };

slide-30
SLIDE 30

Designing a Text Editor

  • Gamma et al., “Design Patterns,”

Chapter 2, 1994

  • Design a “What-You-See-Is-What-

You-Get” (WYSIWYG) editor called Lexi.

slide-31
SLIDE 31

Design Problems

  • 1. Document structure
  • 2. Formatting
  • 3. Embellishing the UI (scroll bars or borders)
  • 4. Supporting multiple look-and-feels
  • 5. Supporting multiple window systems
  • 6. User operations
  • 7. Spelling checking and hyphenation
slide-32
SLIDE 32
  • 1. Document Structure
  • Recursive composition of text and graphics
slide-33
SLIDE 33

Composite Pattern

slide-34
SLIDE 34

Define Class Glyph

  • Basic glyph interface
slide-35
SLIDE 35
  • 2. Formatting (Strategy Pattern)
  • Composition and Compositor
  • Using Strategy Pattern to encapsulate an algorithm and handle objects
slide-36
SLIDE 36
  • 3. Embellishing the User Interface (Decorator)
  • Decorator Pattern: support embellishment by

transparent enclosure

slide-37
SLIDE 37
  • 4. Multiple Look-and-Feels (Abstract Factory)
slide-38
SLIDE 38
  • 5. Multiple Window Systems (Bridge Pattern)
  • We may not be able to apply Abstract Factory directly, because

different OS may have different class structure.

slide-39
SLIDE 39
  • 6. User Operations (Command Pattern)
slide-40
SLIDE 40
  • 7. Spelling Checking and Hyphenation
  • Iterator Pattern to define different set of iterations
slide-41
SLIDE 41

Encapsulating the Analysis

  • Visitor Pattern
slide-42
SLIDE 42

Patterns used for Text Editor Design

  • 1. Composite to represent the document's physical structure,
  • 2. Strategy to allow different formatting algorithms,
  • 3. Decorator for embellishing the user interface,
  • 4. Abstract Factory for supporting multiple look-and-feel standards,
  • 5. Bridge to allow multiple windowing platforms,
  • 6. Command for undoable user operations,
  • 7. Iterator for accessing and traversing object structures, and
  • 8. Visitor for allowing an open-ended number of analytical capabilities

without complicating the document structure's implementation.

slide-43
SLIDE 43

References

  • 1. https://www.tutorialspoint.com/cplusplus
  • 2. https://www.tutorialspoint.com/cplusplus/cpp_classes_objects.htm
  • 3. https://en.wikipedia.org/wiki/Object-oriented_programming
  • 4. Erich Gamma, Richard Helm, Ralph Johnson , John Vlissides, “Design

Patterns,” 1994