1 / 49

Review of C++ Syntax

Review of C++ Syntax. C++: Separate Files. Header files Filenames end with .h Used to store declarations of functions, variables, classes. Source files Store C++ source code. Include header with #include statement. C++: Comments. Single line: // My comment goes here Multi line: /*

effie
Download Presentation

Review of C++ Syntax

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Review of C++ Syntax

  2. C++: Separate Files • Header files • Filenames end with .h • Used to store declarations of functions, variables, classes. • Source files • Store C++ source code. • Include header with #include statement

  3. C++: Comments • Single line: // My comment goes here • Multi line: /* My first comment line Another comment line Yet another comment line */

  4. C++: Data Types • Primitive data types: • char • int • float • double • Modifiers: • Amount of data held: short, long • Use of sign bit: signed, unsigned • User-defined: Build on top of primitive and other user-defined types

  5. C++: Collections of Types • array: • Homogeneous collection of indexed data • struct: • Heterogeneous collection of named data • Public data items by default • class: • Heterogeneous collection of named data • Operations on that data • Private data items by default

  6. C++: Data Declarations • Constants • Literals and fixed values – 5, ‘a’, 4.331 • Variables • Instance of a type • Location in memory whose contents can change during program execution • Constant variable • Variable whose contents are fixed • const keyword

  7. C++: Data Declarations • Enumerated Types: • Assigned names to integer constants • Pointers: • Hold memory address of a variable • De-referenced to access the actual data • *variableName • References: • Provide an alternate name for an object • Used in calling functions • &variableName

  8. C++: Scope • File Scope: • Any declarations not within a block or class. • Global variables that can be used anywhere in file. • Local Scope: • Declared within a block • Holds within a block and any subblocks nested within that block • Class Scope: • Declarations within a class are associated with that class

  9. C++: Scope • Less common scope usage: • Scope operator, ::, allows access to global variable if within a block that contains a local variable of the same name • extern avoids re-declaration of global variable across multiple files • allows you to use variable defined elsewhere • static allows re-declaration of global variables in multiple files

  10. C++: Standard I/O • #include <iostream> • Writing to screen: • cout << variable << “string literal” << endl; • Reading from keyboard: • cin >> variable;

  11. C++: File I/O • #include <fstream> • Use same << and >> operators as with cin and cout • Output Streams: • ofstream fileVariableName(“filename”, ios::out); • If, after declaring the file, fileVariableName equals 0, the file couldn’t be opened • To write, replace cout with the fileVariableName you have chosen (in this case, outFile) • outFile << “Hello World” << endl;

  12. C++: File I/O • Input Streams: • ifstream fileVariableName(“filename”, ios::in); • fileVariableName set to 0 if couldn’t be opened • inFile >> VariableName To Read From File;

  13. C++: Functions • Every function has four parts: • Function name • Parameter list (function inputs) – parameter types and names • Return type (function outputs) • Body, enclosed by curly brackets • An example: double square(double inputValue) { double squareValue = inputValue * inputValue; return squareValue; }

  14. C++: Functions • Every function must end with a return statement if the return type is not void • Function names can be overloaded as long as they have different signatures (parameter lists).

  15. C++: Parameter Passing • Pass by value • Example: double square (double value) • Default mechanism • Make a copy of the argument • Doesn’t change argument when function returns • Pass by reference: • Example: double square(double & value) • Copies address of argument into function • Manipulates underlying data • Default for arrays

  16. C++: Parameter Passing • Why pass by reference? • Faster than pass by value for large objects • Allows you to return more than one thing from a function

  17. C++: Parameter Passing • Best option: constant pass by reference • Example: double square(const double & value) • Uses reference passing for speed • Compiler prevents modification to argument within function body

  18. C++: Dynamic Allocation • Use the new keyword to allocate a new object from free memory. • Creates an object of desired type and returns a pointer to it. • int* myInteger = new int; • int* myIntegerArray = new int[10]; • Returns 0 if unable to allocate memory • Use the delete keyword to free the memory being used by an object. • delete myInteger; • delete [] myIntegerArray;

  19. Review of Classes and OOP

  20. OOP: Classes and Objects • Automobiles: • Lots of different types: • 2002 Toyota Tacoma, Automatic, 4 Passengers • 1995 Chevrolet Camaro, Manual, 4 Passengers • 2001 Volkswagen Jetta, Automatic, 4 Passengers • 2004 Honda Accord, Automatic, 4 Passengers • 1973 Ford Mustang, Manual, 2 Passengers

  21. C++: Classes • Prototype Automobile: • Year • Make • Model • TransmissionType • Passenger Capacity

  22. C++: Classes • Prototype automobile: Class • Designates defining features and functions • Lots of different instances/instantiations of automobiles: Objects • Actual realization of class prototype

  23. C++: Classes • What if there are features that belong to some instances of a class, but not all? • Trucks: • Bed length • Trucks are a specialization: They are all automobiles, but not all automobiles are trucks.

  24. C++: Inheritance Year Make Model TransmissionType PassengerCapacity Automobile IS-A Truck BedLength

  25. C++: Inheritance Vehicle IS-A IS-A IS-A Plane Boat Automobile IS-A Truck

  26. OOP: Data Types • Data Type: • Collection of objects • Set of operations that act on those objects • Integers: • Objects: {MININT,…,-1,0,1,…,MAXINT} • Operations: +, -, *, /, and many more • Other operations are not defined for integers: substring?

  27. OOP: Basic Definitions • Object: • Maintains local state • Performs computations • Object Oriented Programming: • Objects are the fundamental building blocks of implementation • Each object is an instance of some class • Classes are related to each other by inheritance

  28. OOP: Classes • Classes provide: • abstraction • encapsulation • Four components: • Class Name • Data Members • Member Functions • Access Levels – Apply to data members and member functions

  29. OOP: Class Example Rectangle.h #ifndef RECTANGLE_H #define RECTANGLE_H Class Rectangle { public: Rectangle(); // constructor ~Rectangle(); // destructor int getHeight(); // return height int getWidth(); // return width int getArea(); // return area private: int x1, y1, h, w; // (x1,y1) bottom left corner, h height, w width } #endif

  30. OOP: Access Levels • Public: • Data member or function can be accessed or invoked from anywhere in the program • Private: • Accessed or invoked only from the containing class or from a friend function or class • Protected: • Accessed or invoked from the containing class, its subclasses, or from a friend function or class

  31. OOP: Encapsulation • Declare data members of a class to be private or protected. • All functions that only deal with the implementation of the operations should be private. • Must use a provided public function to update or read the internal state of the object.

  32. OOP: Class Example Rectangle.h #ifndef RECTANGLE_H #define RECTANGLE_H Class Rectangle { public: Rectangle(); // constructor ~Rectangle(); // destructor int getHeight(); // return height int getWidth(); // return width int getArea(); // return area private: int x1, y1, h, w; // (x1,y1) bottom left corner, h height, w width } #endif

  33. OOP: Abstraction • Place class specification in .h file • Place class implementation in .cpp file #include “Rectangle.h” int Rectangle::getHeight() { return h;} int Rectangle::getWidth() { return w; } int Rectangle::getArea() { return w * h; } …. Rectangle:: provides the scope for these functions.

  34. OOP: Declaring Objects • Declaration: • Similar to declarations for primitive type data #include “Rectangle.h” int main() { Rectangle r, s; Rectangle *t = &s; } • Provides two rectangle variables and a pointer to a rectangle.

  35. OOP: Invoking Member Functions • Use . (dot operator) to access member functions of class objects. int firstRectangleHeight = r.getHeight(); • Use -> (arrow operator) to access member functions through a pointer. int pointerRectangleHeight = t -> getHeight();

  36. OOP: Two Important Functions • Two important functions should implement for classes: • Constructor – How to instantiate and initialize class • Destructor – What to do to clean up the class when no longer needed

  37. OOP: Constructors • Used to initialize data members of a class • Executed when object is created • Default constructor: • Allocates memory for data objects, but doesn’t initialize • Implicitly defined as public className(); // no arguments when no programmer-defined constructor

  38. OOP: Defining Constructors • Public member function • Name is identical to class name • No return type/return statements Rectangle::Rectangle(int x, int y, int height, int width) { x1 = x; y1 = y; h = height; w = width; } Rectangle r(1,1,3,5) Rectangle *r = new Rectangle(1,1,3,5) • Rectangle r; no longer works if you define a constructor like this! • Once a constructor has been defined, the default no-argument constructor is no longer valid unless the programmer also develops a no-argument constructor.

  39. OOP: Constructors • Workarounds: • Implement no argument constructor public Rectangle::Rectangle() { x1 = 0; y1 = 0; h = 0; w = 0; } • Initialize default values in argument constructor header: public Rectangle::Rectangle(int x = 0; int y = 0; int height = 0; int width = 0)

  40. OOP: Destructors • Frees memory before object disappears • Object goes out of scope • Object is deleted • If not user-defined, frees memory associated with data members. • If member is a pointer, only frees memory for pointer, not the object that is being referenced. • User defined is safest if complex object

  41. OOP: Destructors • Public member function • Name is identical to class name, prepended by a ~ • ~Rectangle() • No return type/return statements • No arguments

  42. OOP: Operator Overloading • Implementing language defined operators for user-defined objects • Test for equality: • int a = 3; int b = 3; if (a == b) • Rectangle r(0,0,1,1); Rectangle s(0,0,2,2); if (r == s) • Need to define == for the context of the Rectangle class • Same x1,y1 start points • Same width, same height • Must adhere to language defined function signature when overloading

  43. OOP: Operator Overloading // tests whether input rectangle s is equal to // our rectangle, given definition on previous slide int Rectangle::operator== (const Rectangle& s) { if (this == &s) return 1; else if ((x1 == s.x1) && (y1 == s.y1) && (h = s.h) && (w = s.w)) return 1; else return 0; } // checks if same object first (this pointer) // then checks for equality in x1,y1,h,w

  44. OOP: Operator Overloading • << operator (useful for cout, printing to screen) • Not a member function, but accesses member variables • Requires friend access Rectangle.h: friend ostream& operator << (ostream &os, const Rectangle &r) Rectangle.cpp: ostream& operator<<(ostream& os, Rectangle& r) { os << “Position is “ << r.x1 << “ “ << r.x2 << endl; os << “Height is “ << r.h << endl; os << “Width is “ << r.w << endl; return os; }

  45. OOP: Inheritance • Bag: Datastructure that allows insertion and deletion of objects • Stack: Datastructure that allows insertion and deletion of objects, objects can only be deleted in a Last In, First Out order • A Stack IS-A Bag • Functions that require a Stack interface for operation can’t use a Bag datastructure, but programs that require a Bag interface could use a Stack

  46. OOP: Inheritance • Derived classes (subclasses) inherit: • All non-private members (data and functions) of the base class • Inherited members preserve the level of access of the base class • Inherited functions maintain the same prototype/signature. • Inherited functions can use the base-class implementation or define their own implementation.

  47. OOP: Inheritance Syntax • In Stack.h class Stack: public Bag denotes that the class Stack is derived from the class Bag • Don’t need to re-declare functions in header or source file for Stack unless constructor/destructor or overriding base version

  48. OOP: Dynamic Binding • With inheritance, pointer or reference to a derived class is implicitly converted to that of the base class. • Example: Rectangle r; Polygon *s = &r; • Dynamic type of Polygon pointer becomes Rectangle • What happens if we call a function on the Polygon pointer that is implemented in both Polygon and Rectangle? • standard typed variable: will call function for variable type • pointer/reference: will call function for dynamic type of pointer

  49. OOP: Virtual Functions • Virtual: • Implement function in base class and derived class • Function has keyword virtual in base class prototype • virtual int myFunction(); • Will call function for dynamic type • In this instance, Rectangle instead of Polygon • Non-virtual: • Implement function in base class and derived class • No virtual keyword • Will call function for true pointer type • Polygon instead of Rectangle

More Related