C++ Review Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Acknowledgement: Adapted from: Brown.

Slides:



Advertisements
Similar presentations
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Advertisements

Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
CSE 374 Programming Concepts & Tools Hal Perkins Winter 2012 Lecture 19 – Introduction to C++
Informática II Prof. Dr. Gustavo Patiño MJ
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
C++ Mini-Course Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion C++ Rulez!
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 CSE 303 Lecture 21 Classes and Objects in C++ slides created by Marty Stepp
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
CS-2303 System Programming Concepts
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
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.
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.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
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.
Recap, Test 1 prep, Composition and Inheritance. Dates Test 1 – 12 th of March Assignment 1 – 20 th of March.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
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.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
C++ Memory Overview 4 major memory segments Key differences from Java
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ REVIEW – POINTERS AND TEST DRIVEN DEVELOPMENT.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
CS 261 – Data Structures Introduction to C Programming.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
Review 1 List Data Structure List operations List Implementation Array Linked List.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
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.
11 Introduction to Object Oriented Programming (Continued) Cats.
1 Introduction to Object Oriented Programming Chapter 10.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Pointers and References. Pointers & Memory 0x000x040x080x0B0x100x140x180x1B0x20.
CSE 374 Programming Concepts & Tools
Overview 4 major memory segments Key differences from Java stack
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
CS410 – Software Engineering Lecture #11: C++ Basics IV
Pointers Revisited What is variable address, name, value?
Dynamic Memory Allocation
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Overview 4 major memory segments Key differences from Java stack
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Classes, Constructors, etc., in C++
CS410 – Software Engineering Lecture #5: C++ Basics III
Pointers and References
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

C++ Review Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Acknowledgement: Adapted from: Brown CS123

C++ Review Part 1: Mechanics

3 C++ is a superset of C New Features include –Classes (Object Oriented) –Templates (Standard Template Library) –Operator Overloading –Slightly cleaner memory operations

4 Some C++ code #ifndef __SEGMENT_HEADER__ #define __SEGMENT_HEADER__ class Point; class Segment { public: Segment(); virtual ~Segment(); private: Point *m_p0, *m_p1; }; #endif // __SEGMENT_HEADER__ Segment.h #include "Segment.h" #include "Point.h" Segment::Segment() { m_p0 = new Point(0, 0); m_p1 = new Point(1, 1); } Segment::~Segment() { delete m_p0; delete m_p1; } Segment.cpp

5 #include "Segment.h" #include Insert header file at this point. Use library header.

6 Header Guards #ifndef __SEGMENT_HEADER__ #define __SEGMENT_HEADER__ // contents of Segment.h //... #endif To ensure it is safe to include a file more than once.

7 Header Guards #ifndef __SEGMENT_HEADER__ #define __SEGMENT_HEADER__ // contents of segment.H //... #endif To ensure it is safe to include a file more than once. If this variable is not defined… Define it. End of guarded area.

8 Circular Includes What’s wrong with this picture? How do we fix it? #include "controller.h" // define gui //... gui.h #include "gui.h" class Controller { //... private: Gui* myGui; //... }; controller.h

9 Forward Declarations In header files, only include what you must. If only pointers to a class are used, use forward declarations. //Forward Declaration class Controller; // define gui //... gui.h //Forward declaration class Gui; class Controller { //... private: Gui* myGui; //... }; controller.h

C++ Review Part 2: Basics

11 What is a pointer? int x = 10; int *p; p = &x; p gets the address of x in memory. p x10

12 What is a pointer? int x = 10; int *p; p = &x; *p = 20; *p is the value at the address p. p x20

13 What is a pointer? int x = 10; int *p = NULL; p = &x; *p = 20; Declares a pointer to an integer & is address operator gets address of x * dereference operator gets value at p

14 Allocating memory using new int *p = new int; new can be thought of a function with slightly strange syntax new allocates space to hold the object. new calls the object’s constructor. new returns a pointer to that object.

15 Deallocating memory using delete // allocate memory Point *p = new Point(5, 5);... // free the memory delete p; For every call to new, there must be exactly one call to delete.

16 Using new with arrays int x = 10; int* nums1 = new int[10]; // ok int* nums2 = new int[x]; // ok Initializes an array of 10 integers on the heap. C++ equivalent of the following C code int* nums = (int*)malloc(x * sizeof(int));

17 Using new with multidimensional arrays int x = 3, y = 4; int** nums3 = new int[x][4];// ok int** nums4 = new int[x][y];// BAD! Initializes a multidimensional array Only the first dimension can be a variable. The rest must be constants. Use single dimension arrays to fake multidimensional ones

18 Using delete on arrays // allocate memory int* nums1 = new int[10]; int* nums3 = new int[x][4][5];... // free the memory delete[] nums1; delete[] nums3; Have to use delete[].

19 Destructors delete calls the object’s destructor. delete frees space occupied by the object. A destructor cleans up after the object. Releases resources such as memory.

20 Destructors – an Example class Segment { public: Segment(); virtual ~Segment(); private: Point *m_p0, *m_p1; }; Segment::Segment() { m_p0 = new Point(0, 0); m_p1 = new Point(1, 1); } Segment::~Segment() { if (m_p0) delete m_p0; if (m_p1) delete m_p1; }

21 New vs Malloc MallocNew Standard C FunctionOperator (like ==, +=, etc.) Used sparingly in C++; used frequently in COnly in C++ Used for allocating chunks of memory of a given size without respect to what will be stored in that memory Used to allocate instances of classes / structs / arrays and will invoke an object’s constructor Returns void* and requires explicit castingReturns the proper type Returns NULL when there is not enough memory Throws an exception when there is not enough memory Every malloc() should be matched with a free() Every new/new[] should be matched with a delete/delete[] Never mix new/delete with malloc/free

22 Classes vs Structs Default access specifier for classes is private; for structs it is public Except for this difference, structs are functionally the same as classes, but the two are typically used differently: structs should be thought of as lightweight classes that contain mostly data and possibly convenience methods to manipulate that data and are hardly ever used polymorphically

23 struct Point { int x; int y; Point(int a, int b) : x(a), y(b) { } distance to another point double distance(const Point &pnt) { int dx = m_x – pnt.x; int dy = m_y – pnt.y; return math.sqrt(dx*dx + dy*dy); } }; class Segment { public: Segment(); virtual ~Segment(); void setPoints(int x0, int y0, int x1, int y1); protected: Point *m_p0, *m_p1; }; void Segment::setPoints(int x0, int y0, int x1, int y1) { m_p0 = new Point(x0, y0); m_p1 = new Point(x1, y1); }

24 Syntactic Sugar “ -> ” Point *p = new Point(5, 5); // Access a member function: (*p).move(10, 10); // Or more simply: p->move(10, 10);

25 Stack vs. Heap On the Heap / Dynamic allocation On the Stack / Automatic allocation drawStuff() { Point *p = new Point(); p->move(10,10); //... } drawStuff() { Point p(); p.move(5,5); //... } What happens when p goes out of scope?

26 Summary with Header File begin header guard #ifndef __SEGMENT_HEADER__ #define __SEGMENT_HEADER__ class Point; class Segment { public: Segment(); virtual ~Segment(); protected: Point *m_p0, *m_p1; }; #endif // __SEGMENT_HEADER__ Segment.h header file forward declaration class declaration constructor destructor end header guard member variables need semi-colon

27 C++ Review Part 3: References

28 Passing by value void Math::square(int i) { i = i*i; } int main() { int i = 5; Math::square(i); cout << i << endl; }

29 Passing by reference void Math::square(int &i) { i = i*i; } int main() { int i = 5; Math::square(i); cout << i << endl; }

30 What is a reference? An alias – another name for an object. int x = 5; int &y = x; // y is a // reference to x y = 10; What happened to x? What happened to y?

31 What is a reference? An alias – another name for an object. int x = 5; int &y = x; // y is a // reference to x y = 10; What happened to x? What happened to y? – y is x.

32 Why are they useful? Unless you know what you are doing, do not pass objects by value; either use a pointer or a reference. References are in effect the same as pointers, but safer → better programming style. Can be used to return more than one value (pass multiple parameters by reference)

33 How are references different from Pointers? Reference Pointer int &a; int *a; int a = 10; int b = 20; int &c = a; c = b; int a = 10; int b = 20; int *c = &a; c = &b;

34 C++ Review Part 4: const

35 Introducing: const void Math::printSquare(const int &i){ i = i*i; cout << i << endl; } int main() { int i = 5; Math::printSquare(i); Math::printCube(i); } Won’t compile.

36 Can also pass pointers to const void Math::printSquare(const int *pi) { *pi = (*pi) * (*pi); cout << pi << endl; } int main() { int i = 5; Math::printSquare(&i); Math::printCube(&i); } Still won’t compile.

37 Declaring things const const River nile; const River* nilePc; River* const nileCp; const River* const nileCpc

38 Read pointer declarations right to left // A const River const River nile; // A pointer to a const River const River* nilePc; // A const pointer to a River River* const nileCp; // A const pointer to a const River const River* const nileCpc

39 Let’s Try References River nile; const River &nileC = nile; // Will this work? River &nile1 = nileC;

40 How does const work here? void Math::printSquares(const int &j, int &k) { k = k*k; // Does this compile? cout << j*j << “, ” << k << endl; } int main() { int i = 5; Math::printSquares(i, i); }

41 Returning const references is OK class Point { public: const double &getX() const; const double &getY() const; void move(double dx, double dy); protected: double m_x, m_y; }; const double & Point::getX() const { return m_x; } Function won’t change *this.

42 C++ Review Part 5: Inheritance

43 How does inheritance work? #include “Segment.h” class DottedSegment : public Segment { // DottedSegment declaration }; must include parent header file DottedSegment publicly inherits from Segment

44 virtual Static binding: compile-time, the compiler binds the method call with draw() of sPtr's class Dynamic binding: run-time, the method call is bound with draw() of the class whose object Ptr is pointing to In C++ methods are static by default you have to declare the method virtual if you want dynamic binding class DottedSegment: public Segment {…}... Segment *sPtr = new DottedSegment(); sPtr.draw(); // which version get invoked? // Segment's or DottedSegment's?

45 pure virtual functions In the super class's definition: –virtual void draw() = 0; This function must be implemented in a subclass. class Segment { virtual void draw() = 0;... class DottedSegment: public Segment {…} virtual void draw() { #implementation...

46 this is important virtual Make you declare your destructors virtual; if you do not declare a destructor a non-virtual one will be defined for you Segment(); virtual ~Segment();

47 C++ Review Part 6: Libraries

48 Namespaces Namespaces reduce naming conflicts Most standard C++ routines and classes and under the std namespace –Any standard C routines (malloc, printf, etc.) are defined in the global namespace #include using namespace std;... cout << "Hello!";...

49 STL Standard Template Library Contains well-written, templated implementations of MOST data structures and algorithms –Templates allow generic programming –Allows you to easily store anything without writing a container yourself Will give you the most hideous compile errors ever if you use them even slightly incorrectly!

50 STL example #include using namespace std; typedef vector PointVector; typedef PointVector::iterator PointVectorIter; PointVector v; v.push_back(Point(3, 5)); PointVectorIter iter; for(iter = v.begin(); iter != v.end(); ++iter){ Point &curPoint = *iter; }