C++ AND C ID1218 Lecture 092009-11-25 Christian Schulte Software and Computer Systems School of Information and Communication Technology.

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Advertisements

SPL/2010 Pointers and Parameter Passing in C++ 1.
Kernighan/Ritchie: Kelley/Pohl:
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,
Road Map Introduction to object oriented programming. Classes
Chapter 14: Overloading and Templates
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Classes: A Deeper Look Systems Programming.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
GETTING STARTED WITH C++ ID1218 Lecture Christian Schulte Software and Computer Systems School of Information and Communication.
Lecture 9 Concepts of Programming Languages
C++: MEMORY MANAGEMENT, SUMMARY ID1218 Lecture Christian Schulte Software and Computer Systems School of Information and Communication.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Review of C++ Programming Part II Sheng-Fang Huang.
OOP Languages: Java vs C++
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.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
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.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
C++ Review (3) Structs, Classes, Data Abstraction.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
The Big Three Based on Weiss “Data Structures and algorithm Analysis CS240 Computer Science II.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
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:
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
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.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
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.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Programming with ANSI C ++
Introduction to Classes
This pointer, Dynamic memory allocation, Constructors and Destructor
Lecture 9 Concepts of Programming Languages
Introduction to Classes
Object Oriented Programming in java
Java Programming Language
CS410 – Software Engineering Lecture #5: C++ Basics III
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Lecture 9 Concepts of Programming Languages
Presentation transcript:

C++ AND C ID1218 Lecture Christian Schulte Software and Computer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden

L09, ID1218, Christian Schulte 2 Overview  Objects  Inheritance  Templates  Operators  C

L09, ID1218, Christian Schulte 3 Reading Suggestions  All of you thorough reading of chapters 4, 6, 12

Objects and Classes L09, ID1218, Christian Schulte

L09, ID1218, Christian Schulte 5 An Integer Cell class IntCell { private: int x; public: IntCell(int y=0) { x=y; } int get() { return x; } void set(int y) { x=y; } };

L09, ID1218, Christian Schulte 6 Accessors vs Mutators  Fundamental difference set:changes object state (mutator) get:does not change state (accessor)  In C++ accessors need to be declared const int get() const { return x; } compiler enforces that state is not changed well, can be controlled with const-cast…

L09, ID1218, Christian Schulte 7 Initializer Lists  Rewrite constructor to IntCell(int y=0) : x(y) {} after colon: comma separated list in order of declaration of members  Old version first initialize with default constructor for member then assign value  New version only initialized  Matters for non primitive data members!

L09, ID1218, Christian Schulte 8 Copying and Assignment  Copying is controlled by copy constructor IntCell(const IntCell& c) : x(c.x) {}  Assignment is controlled by assignment operator IntCell& operator=(const IntCell& c) { if (this != &c) x=c.x; return *this; }  These are synthesized by compiler if missing required for resource management

L09, ID1218, Christian Schulte 9 A Different IntCell  Maintain integer via pointer class IntCell { private: int* x; public: IntCell(int y=0) : x(new int) { *x = y; } … } how to manage the allocated memory?

L09, ID1218, Christian Schulte 10 Copy Constructor IntCell(const IntCell& c) : x(new int) { *x = *c.x; }  Used for parameter passing  Used for initialization (assume c is IntCell ) IntCell d(c);

L09, ID1218, Christian Schulte 11 Assignment Operator IntCell& operator=(const IntCell& c) { if (this != &c) { delete x; x = c.x; } return *this; }  Returns an IntCell to allow assignment sequences a = b = c;

L09, ID1218, Christian Schulte 12 Destructor ~IntCell() { delete x; }  When object is deleted by delete (for heap allocated) by going out of scope (for automatically allocated) destructor is invoked for resource management

L09, ID1218, Christian Schulte 13 Default Constructor  A constructor with no arguments (or all arguments with default values) automatically generated, if no constructors provided  Important for initialization IntCell c; invokes the default constructor

Fine Points for Objects L09, ID1218, Christian Schulte

L09, ID1218, Christian Schulte 15 Friends  Grant access to class internals class ListNode { friend class IntQueue; …  Can be fine-grained: for functions for member functions

L09, ID1218, Christian Schulte 16 Static Members  Static member is part of class, not of instance maintain data that is shared among all instances of a class  Requires declaration and definition  Declaration use keyword static done in header  Definition use class name done in implementation

L09, ID1218, Christian Schulte 17 Static Members: Header class Tracked { private: static int noi; public: Tracked() { noi++; … } … };

L09, ID1218, Christian Schulte 18 Static Members: Implementation  Can be initialized int Tracked::noi = 0;

L09, ID1218, Christian Schulte 19 Namespaces  Organize multiple functions, classes, etc together similar to Java package namespace N { class C … }

L09, ID1218, Christian Schulte 20 Using Namespaces  Inside the namespace, as always C  Outside namespace N::C  Convenience: make available single class using N::C; namespace using namespace N;  Reference to C in global namespace ::C

L09, ID1218, Christian Schulte 21 Incomplete Class Declaration  Mutual recursive definitions common through pointers class A { … B* data; }; class B { … A* data; };  Use incomplete class definition class B; class A { … B* data; }; class B { … A* data; }; only limited use of incompletely declared class allowed

Inheritance L09, ID1218, Christian Schulte

L09, ID1218, Christian Schulte 23 Inheritance  Construct classes from other classes inherit members and member functions  Supports public and private inheritance public is normal behavior (as in Java)  Supports multiple inheritance inherit from multiple classes not discussed here

L09, ID1218, Christian Schulte 24 Person Class class Person { private: int _pn; const char* _n; public: Person(int pn, const char* n) : _pn(pn), _n(n) {} int pn() const { return _pn; } const char* name() const { return _n; } };

L09, ID1218, Christian Schulte 25 Student Class class Student : public Person { private: int _pts; public: Student(int pn, const char* n, int pts) : Person(pn,n), _pts(pts) {} int pts() const { return _pts; }

L09, ID1218, Christian Schulte 26 Adding Printing class Person { … void print(ostream& o = std::cout) const { o << name() << "(" << pn << ")"; } }; class Student { … void print(ostream& o = std::cout) const { Person::print(o); o << "[" << pts() << "]"; } };

L09, ID1218, Christian Schulte 27 Example Persons…  Works okay Person p(1234, "Alice"); Student s(5678, "Bob", 12); p.print(); s.print(); std::cout << s.name() << std::endl;

L09, ID1218, Christian Schulte 28 Things Going Wrong…  Which print gets called… Student s(1234, "Carl", 34); void printme(const Person& p) { p.print(); } printme(s); uses Person::print rather than Student::print known as static dispatch: based on compile-time type of p

L09, ID1218, Christian Schulte 29 Dynamic Dispatch  Use runtime type for finding member function default behavior in Java in C++: mark member functions as virtual  Fix printing in base class class Person { … virtual void print(ostream& o=std::cout) const { … };

L09, ID1218, Christian Schulte 30 Defaults with Inheritance  Copy constructor invokes copy constructor on base classes invokes copy constructor on newly added data members  Assignment operator invokes assignment operator on base classes invokes assignment operator on newly added data members  Destructor invokes destructors on newly added data members invokes destructors on base classes

L09, ID1218, Christian Schulte 31 Explicit Implementation class Student { … Student(const Student& s) : Person(s), _pts(s._pts) {} ~Student() { // Invokes ~Person() automatically! } Student& operator=(const Student& s) { if (this != &s) { Person::operator=(s); _pts = s._pts; } return *this; } };

L09, ID1218, Christian Schulte 32 Virtual Destructor  Consider example Student* s = new Student(3456, "Deb", 2); Person* p = s; delete p; uses static dispatch: destructor of Person!  Must declare destructor virtual in baseclass virtual ~Person() {}

L09, ID1218, Christian Schulte 33 Abstract Methods and Classes  Member functions can be declared abstract in base class declare as virtual declaration followed by = 0;  Base class for geometric shape class Shape { public: virtual double area() const = 0; … };

L09, ID1218, Christian Schulte 34 A Rectangle Class class Rect : public Shape { public: … virtual double area() const { return size*size; } };  Not longer abstract abstract class contains at least one abstract method only non-abstract classes allow instances!

L09, ID1218, Christian Schulte 35 Type Conversions  Assume we know that p is a student, really Person* p = new Student(123,"Eva",2);  Use dynamic cast Student* s = dynamic_cast (p); performs check and cast at runtime returns NULL, if not a Student

Templates L09, ID1218, Christian Schulte

L09, ID1218, Christian Schulte 37 Generic Programming  Common example: collections in Java all members are of type Object has limitations: primitive types (requires boxing), requires casts checked at runtime, … fixed in Java 5  Supported in C++ by templates abstract over types and values applicable to functions, classes, and member functions

L09, ID1218, Christian Schulte 38 Integer List Class class IntList { private: int h; IntList* t; public: IntList(int h0, IntList* t0) : h(h0), t(t0) {} int head() const { return h; } … };  Does not depend on type of list elements!

L09, ID1218, Christian Schulte 39 Generic List Class template class List { private: E h; List * t; public: List(const E& h0, List * t0) : h(h0), t(t0) {} const E& head() const { return h; } … };

L09, ID1218, Christian Schulte 40 Using the Generic List Class  List of integers List * il = new List (4,NULL);  List of floats List * fl = new List (4.0,NULL);

L09, ID1218, Christian Schulte 41 Template Functions template void ex(T& x, T& y) { T t = x; x = y; y = t; }  Use as follows int x = 4; int y = 5; ex(x,y); uses automatic resolution of types complicated process, in particular with overloading  Can be explicit ex (x,y);

L09, ID1218, Christian Schulte 42 Compilation Model  Still most useful strategy put everything in the header file both declaration and definition compiler will produce code if needed  Other strategies available explicit instantiation in implementation template class List ; export directive

Operator Overloading L09, ID1218, Christian Schulte

L09, ID1218, Christian Schulte 44 Operator Overloading  Many operators ( +, [] ) can be overloaded in C++ useful for concise programs  Different strategies for overloading make operator member function make operator function  Details, see book: chapter 5

L09, ID1218, Christian Schulte 45 Overloading Printing  Overload the output operator << std::ostream& operator<<(ostream& o, const Person& p) { p.print(o); return o; }

L09, ID1218, Christian Schulte 46 Overloading Memory Management  Memory management for class instances defined by operators static void* operator new(size_t); static void operator delete(void*); where void* pointer to anything where size_t integer type for specifying size discussed later  Can be used to change memory allocation policy per class

C Programming L09, ID1218, Christian Schulte

L09, ID1218, Christian Schulte 48 Major Differences…  No classes use structs (see later)  No references use pointers  No overloading  No templates  No default parameters  All local variable declarations must be at beginning of function  Memory management  Libraries

L09, ID1218, Christian Schulte 49 The Struct Type  Combine data into one structure struct IntPair { int x; int y; };  Also available in C++, corresponds to class IntPair { public: int x; int y; };

L09, ID1218, Christian Schulte 50 Preprocessor Macros  Conditional compilation  Textual substitution #define FOOVALUE 1  Macros #define max(x,y) (x>y?x:y) unsafe! unsafe! things go wrong b = max(a--,c--);

L09, ID1218, Christian Schulte 51 C-Style Memory Management  Can also be useful in C++  Headers required in C: #include in C++ #include

L09, ID1218, Christian Schulte 52 C-Style Memory Management  Allocate n bytes from heap void* malloc(size_t n);  Free memory block p obtained by malloc void free(void* p);  Never mix new+delete with malloc+free never use delete on malloc block and vice versa

L09, ID1218, Christian Schulte 53 Allocating Memory  In order to allocate memory know the size in bytes sizeof cast to appropriate type static_cast  Allocate memory for array of integers with 10 elements int* a = static_cast ( malloc(10*sizeof(int)); in C: instead of static_cast use (int*)

L09, ID1218, Christian Schulte 54 Pitfall…  What is the difference between C* c = new C; and C* c = static_cast ( malloc(sizeof(C)); no default constructor called! same difference for delete versus free : no destructor called!

Summary L09, ID1218, Christian Schulte

L09, ID1218, Christian Schulte 56 Summary  Objects and classes constructors: default, copy assignment operator destructor virtual member functions and abstract classes  Templates generic classes and functions  C different memory management many features of C++ missing