Week 14 - Wednesday CS222.

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

Inheritance Inheritance Reserved word protected Reserved word super
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CS-2303 System Programming Concepts
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
Classes Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd Spetember 2006.
Chapter 12: Adding Functionality to Your Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
Inheritance in C++ CS-1030 Dr. Mark L. Hornick.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Week 1 - Friday.  What did we talk about last time?  Basic programming model  Other Java stuff  References  Static  Inner classes  Exceptions.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 4 – August 30, 2001.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Week 14 - Wednesday.  What did we talk about last time?  More C++  new  delete  Differences for structs  OOP.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
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 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Classes, Interfaces and Packages
Overview of C++ Polymorphism
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Week 13 - Friday.  What did we talk about last time?  Server communications on a socket  Function pointers.
Data Structures Lecture 4: Classes in C++ Azhar Maqsood NUST Institute of Information Technology (NIIT)
Memory Management.
EGR 2261 Unit 13 Classes Read Malik, Chapter 10.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Computer Organization and Design Pointers, Arrays and Strings in C
C++ Templates.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
7. Inheritance and Polymorphism
Andy Wang Object Oriented Programming in C++ COP 3330
Inheritance and Polymorphism
Polymorphism.
Review: Two Programming Paradigms
Week 14 - Monday CS222.
Object Oriented Programming
Templates.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Introduction to Classes
Classes and Data Abstraction
OOP Paradigms There are four main aspects of Object-Orientated Programming Inheritance Polymorphism Abstraction Encapsulation We’ve seen Encapsulation.
Java Programming Language
Dr. Bhargavi Dept of CS CHRIST
Classes, Constructors, etc., in C++
CISC/CMPE320 - Prof. McLeod
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
Object-Oriented Programming
Overview of C++ Polymorphism
Java Programming Language
Review of Previous Lesson
Lecture 10 Concepts of Programming Languages
Chapter 9 Introduction To Classes
CS410 – Software Engineering Lecture #8: Advanced C++ III
Final Exam Review Inheritance Template Functions and Classes
C++ Object Oriented 1.
Lecture 6: Polymorphism
Presentation transcript:

Week 14 - Wednesday CS222

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

Questions?

Project 6

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

More C++

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.

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

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

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

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

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

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);

OOP in C++

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

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

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

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

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++; }

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

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

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

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

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

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

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

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

C++ Madness

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

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

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; }

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;

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!)

(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;

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

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

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?

Templates

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

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

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

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; };

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

Quiz

Upcoming

Next time… STL Lab 14

Reminders Keep working on Project 6 Due next Friday