Presentation is loading. Please wait.

Presentation is loading. Please wait.

Week 14 - Wednesday CS222.

Similar presentations


Presentation on theme: "Week 14 - Wednesday CS222."— Presentation transcript:

1 Week 14 - Wednesday CS222

2 Last time What did we talk about last time? Function pointers
Introduced C++

3 Questions?

4 Project 6

5 Quotes If you think C++ is not overly complicated, just what is a protected abstract virtual base pure virtual private destructor, and when was the last time you needed one? Tom Cargill

6 More C++

7 Default parameter values
C++ also allows you to specify default values for function parameters If you call a function and leave off those parameters, the default values will be used Default parameters are only allowed for the rightmost grouping of parameters void build(int width = 2, int height = 4) { cout << "We built this house with " << width << " by " << height << "s."; } build(); //We built this house with 2 by 4s. build(3); //We built this house with 3 by 4s. build(6, 8); //We built this house with 6 by 8s.

8 C++ example Let's write a complete C++ program that reads in:
A string An integer Then, it prints out the string however many times the integer specified

9 The new keyword When you want to dynamically allocate memory in C++, you use new (instead of malloc()) No cast needed It "feels" a lot like Java int* value = new int(); //make an int int* array = new int[100]; //array of ints Wombat* wombat = new Wombat(); //make a Wombat Wombat* zoo = new Wombat[100]; //makes 100 Wombats with the default constructor

10 The delete keyword When you want to free dynamically allocated memory in C++, use delete (instead of free()) If an array was allocated, you have to use delete[] int* value = new int(); //make an int delete value; Wombat* wombat = new Wombat(); delete wombat; Wombat* zoo = new Wombat[100]; delete[] zoo; //array delete needed

11 C standard libraries You can compile C code with C++
Weird things can happen, but we aren't going into those subtle issues However, you now know and love the standard C libraries You can use them in C++ too You just have to include different header files C Library Header C++ Equivalent Purpose ctype.h cctype Character manipulation limits.h climits Constants for integer limits math.h cmath Math functions stdio.h cstdio C I/O functions stdlib.h cstdlib Random values, conversion, allocation string.h cstring Null-terminated string manipulation time.h ctime Time functions

12 Structs in C++ A struct in C++ is actually just a class where all the members are public You can even put methods in a struct in C++ Otherwise, it looks pretty similar You don't have to use the struct keyword when declaring struct variables Except in cases when it is needed for disambiguation

13 Example Here's a TreeNode struct in C++
Write a tree insertion with the following signature struct TreeNode { int value; TreeNode* left; TreeNode* right; }; void insert(TreeNode* &root, int data);

14 OOP in C++

15 Object Oriented Programming
Let's see how objects work in C++ by looking at classically important elements of OOP Encapsulation Dynamic dispatch Polymorphism Inheritance Self-reference

16 Encapsulation Information hiding
We want to bind operations and data tightly together Consequently, we don't want you to touch our privates Encapsulation in C++ is provided by the private and protected keywords Unlike Java, you mark sections as public, private, or protected, not individual members and methods Hardcore OOP people think that all data should be private and most methods should be public

17 Encapsulation example
class A { private: int a; public: int getA() return a; } void setA(int value) a = value; };

18 Inheritance Allows code reuse Is thought of as an "is-a" relationship
C++ allows multiple inheritance, but you should only use it if you know what you're doing, usually as part of a design pattern Deriving a subclass usually means creating a "refined" or "more specific" version of a superclass

19 Inheritance example class B : public A { //has member and methods from A }; class C : public A { private: //has A stuff and more int c; public: int getC(){ return c; } void increment() { c++; }

20 Polymorphism A confusing word whose underlying concept many programmers misunderstand Polymorphism is when code is designed for a superclass but can be used with a subclass If AudiRS5 is a subtype of Car, then you can use an AudiRS5 where you could use a Car

21 Polymorphism example void drive( Car* c ); //defined somewhere … class AudiRS5 : public Car {}; Car car; AudiRS5 audi; drive( &audi ); //okay drive( &car ); //okay

22 Dynamic dispatch Polymorphism can be used to extend the functionality of an existing method using dynamic dispatch In dynamic dispatch, the method that is actually called is not known until run time

23 Dynamic dispatch example
class A { public: virtual void print() { cout << "A"; } }; class B : public A { public: void print() { cout << "B"; }

24 Dynamic dispatch example
A a; B b; A* p; a.print(); // A b.print(); // B p = &a; p->print(); // A p = &b; p->print(); // B

25 Self-reference Objects are able to refer to themselves
This can be used to explicitly reference variables in the class Or, it can be used to provide the object itself as an argument to other methods Self-reference in C++ is provided in part through the this keyword this is a pointer to the object you're inside of

26 Self reference example
class Stuff { private: int things; public: void setThings(int things) this->things = things; } };

27 Self reference example
class SelfAdder { public: void addToList(List& list) list.add(this); } };

28 C++ Madness

29 Dividing up code In industrial strength C++ code, the class declaration is usually put in a header file (.h) while the class definition is in an implementation file (.cpp) Benefits: Easy to see members and methods Header files can be sent to clients without divulging class internals Separate compilation (faster) Easier to take care of circular dependencies

30 Dividing up code header
class Complex { double real; double imaginary; public: Complex(double realValue = 0, double imaginaryValue = 0); ~Complex(void); double getReal(); double getImaginary(); };

31 Dividing up code implementation
Complex::Complex(double realValue, double imaginaryValue) { real = realValue; imaginary = imaginaryValue; } Complex::~Complex(void) {} double Complex::getReal() { return real; } double Complex::getImaginary() { return imaginary; }

32 Overloading operators
In C++, you can overload operators, meaning that you can define what + means when used with classes you design Thus, the following could be legal: Hippopotamus hippo; Sandwich club; Vampire dracula = club + hippo;

33 Overloading operators
But, what does it mean to "add" a Hippopotamus to a Sandwich and get a Vampire? Overloading operators is a bad idea You can get confusing code Most languages don't allow it It C++ it is useful in two cases: To make your objects easy to input/output using iostream To perform mathematical operations with numerical classes (like Complex!)

34 (Partial) overloading operators header
Complex& operator=( const Complex& complex ); Complex operator+( const Complex& complex ) const; Complex operator-( const Complex& complex ) const; Complex operator-() const; Complex operator*( const Complex& complex ) const;

35 (Partial) overloading operators implementation
Complex& Complex::operator= ( const Complex& complex ) { real = complex.real; imaginary = complex.imaginary; return *this; }

36 Programming practice Let's finish the Complex type
Then, we can ask the user to enter two complex numbers We can do the appropriate operation with them

37 What's all that const? const, of course, means constant in C++
In class methods, you'll see several different usages Const methods make a guarantee that they will not change the members of the object they are called on int countCabbages() const; Methods can take const arguments void insert(const Coin money); Methods can take const reference arguments void photograph(const Castle& fortress); Why take a const reference when references are used to change arguments?

38 Templates

39 Templates Allow classes and functions to be written with a generic type or value parameter, then instantiated later Each necessary instantiation is generated at compile time Appears to function like generics in Java, but works very differently under the covers Most of the time you will use templates, not create them

40 Template method example
template<class T> void exchange(T& a, T& b ) { T temp = a; a = b; b = temp; }

41 Template classes You can make a class using templates
The most common use for these is for container classes e.g. you want a list class that can be a list of anything The STL filled with such templates Unfortunately, template classes must be implemented entirely in the header file C++ allows template classes to be separate from their headers, but no major compiler fully supports it

42 Template class example
template<class T> class Pair { private: T x; T y; public: Pair( const T& a, const T& b ) { x = a; y = b; } T getX() const { return x; } T getY() const { return y; } void swap() { T temp = x; x = y; y = temp; };

43 Programming practice Let's write an ArrayList class with templates!

44 Quiz

45 Upcoming

46 Next time… STL Lab 14

47 Reminders Keep working on Project 6 Due next Friday


Download ppt "Week 14 - Wednesday CS222."

Similar presentations


Ads by Google