Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "C++ AND C ID1218 Lecture 092009-11-25 Christian Schulte Software and Computer Systems School of Information and Communication Technology."— Presentation transcript:

1 C++ AND C ID1218 Lecture 092009-11-25 Christian Schulte cschulte@kth.se Software and Computer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden

2 L09, 2009-11-25ID1218, Christian Schulte 2 Overview  Objects  Inheritance  Templates  Operators  C

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

4 Objects and Classes L09, 2009-11-25 4 ID1218, Christian Schulte

5 L09, 2009-11-25ID1218, 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; } };

6 L09, 2009-11-25ID1218, 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…

7 L09, 2009-11-25ID1218, 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!

8 L09, 2009-11-25ID1218, 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

9 L09, 2009-11-25ID1218, 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?

10 L09, 2009-11-25ID1218, 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);

11 L09, 2009-11-25ID1218, 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;

12 L09, 2009-11-25ID1218, 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

13 L09, 2009-11-25ID1218, 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

14 Fine Points for Objects L09, 2009-11-25 14 ID1218, Christian Schulte

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

16 L09, 2009-11-25ID1218, 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

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

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

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

20 L09, 2009-11-25ID1218, 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

21 L09, 2009-11-25ID1218, 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

22 Inheritance L09, 2009-11-25 22 ID1218, Christian Schulte

23 L09, 2009-11-25ID1218, 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

24 L09, 2009-11-25ID1218, 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; } };

25 L09, 2009-11-25ID1218, 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; }

26 L09, 2009-11-25ID1218, 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() << "]"; } };

27 L09, 2009-11-25ID1218, 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;

28 L09, 2009-11-25ID1218, 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

29 L09, 2009-11-25ID1218, 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 { … };

30 L09, 2009-11-25ID1218, 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

31 L09, 2009-11-25ID1218, 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; } };

32 L09, 2009-11-25ID1218, 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() {}

33 L09, 2009-11-25ID1218, 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; … };

34 L09, 2009-11-25ID1218, 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!

35 L09, 2009-11-25ID1218, 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

36 Templates L09, 2009-11-25 36 ID1218, Christian Schulte

37 L09, 2009-11-25ID1218, 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

38 L09, 2009-11-25ID1218, 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!

39 L09, 2009-11-25ID1218, 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; } … };

40 L09, 2009-11-25ID1218, 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);

41 L09, 2009-11-25ID1218, 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);

42 L09, 2009-11-25ID1218, 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

43 Operator Overloading L09, 2009-11-25 43 ID1218, Christian Schulte

44 L09, 2009-11-25ID1218, 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

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

46 L09, 2009-11-25ID1218, 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

47 C Programming L09, 2009-11-25 47 ID1218, Christian Schulte

48 L09, 2009-11-25ID1218, 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

49 L09, 2009-11-25ID1218, 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; };

50 L09, 2009-11-25ID1218, 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--);

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

52 L09, 2009-11-25ID1218, 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

53 L09, 2009-11-25ID1218, 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*)

54 L09, 2009-11-25ID1218, 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!

55 Summary L09, 2009-11-25 55 ID1218, Christian Schulte

56 L09, 2009-11-25ID1218, 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


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

Similar presentations


Ads by Google