04cpphandout

04cpphandout - Data abstraction with C+ classes A data...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Data abstraction with C++ classes A data structure for dates in C: struct Date { int month, day, year } void setMonth(struct Date*,int); //Note: ANSI C function prototypes from C++ void setDay(struct Date*,int); void printDate(Date*) .... What's the problem? Closer coupling is possible in C++: struct Date { int month, day, year void set(int m,int d,int y) { month=m; day=d; year=y; } void print(); //Implement elsewhere ... } C++ adds syntax of class to restrict access to data members: class Date { int month, day, year public: void setMonth(m) { if (m > 0 && m < 32) month=m; } void print(); //Implemented elsewhere. .. ... }; Inheritance is called "derivation" in C++ #include <stdio.h> #include <assert.h> #include <iostream.h> #include <ctype.h> //Interface for a simple class, vector: class vector { int sz; //number of elements int* v; //pointer to integers (dynamic array) public: vector(int size); //constructor: allocates v with sz int elements ~vector(); //destructor: also dealloactes v int& operator[](int); //Overloaded array operator int size() { return sz; } }; //Implementation of class vector member functions: vector::vector(int size) //constructor { assert(size > 0); sz = size; v = new int[sz]; //allocate an array of size ints dynamically
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 4

04cpphandout - Data abstraction with C+ classes A data...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online