01 CPP Classes
01 CPP Classes
Swedish connection: Bjarne Stoustrup borrowed from Simula (67) Simulating classes of real world objects Version 1.0 released by AT&T in 1986 Version 2.0 in 1990 (added multiple inheritance) Version 3.0 in 1992 (templates) ANSI standard in 1996 (exception handling, run time type info) C++ became dominant OOPL in early 90's Now Java and C# challenge
C structs
A data structure for dates in C:
struct Date { int month, day, year; }; int set(struct Date*, int m, int d, int y); int print(struct Date*);
No way to control access to data (obscure side effects) No way to prevent assigning an illegal value to month Changing representation of Date breaks all client code
April 13
C++ structs
C++ provides for closer coupling of data and functions:
struct Date { int month, day, year; void set(int m, int d, int y); void print(); //implement elsewhere };
Procedural abstraction hides details of code in functions Data abstraction couples data structure and functions
April 13
Member functions
What can we add to Date to allow access to month?
class Date { int month, day, year; public: void set(int m, int d, int y); void print(); //implement elsewhere int getMonth() { return month; } };
Pros and cons of this approach? inline function is efficient, though it tends to break information hiding
Lets define set() and protects the month data: void Date :: set(int m, int d, int y) { assert(m >= 1 && m <= 31); month = m; }
April 13 5
//Create an array of various shapes Shape* shapes[10]; //Why is this legal? shapes[0] = new Circle(Point(20,30),7); //assign a Circle shapes[1] = new Triangle(Point(50,50),Point(30,30),Point(40,40)); //... maybe assign other shapes, Rectangles, Squares, etc. for (int i=0; i < 10; i++) //draw all the shapes shapes[i]->draw(); //each shape draws itself! } Why do we say that elements of shapes array are polymorphic? How does polymorphic design support Open-Closed principle?
April 13 9
switch (shapes[i]->isa) //each Shape derived class has an isa data member { case(triangle) Triangle::draw(); //test enumeration case(circle) Circle::draw(); //run specific draw()
// ...
Why is the dynamic binding version better for big, growing programs?
April 13 10