Object Oriented Programming In C

Transcription

Introduction and motivationOOP features and conceptsQuick applicationConclusionsObject Oriented Programming in CRadu Grigorasradu.grigoras10@gmail.comUniversity of HamburgFaculty of Mathematics, Informatics and Natural SciencesDepartment of InformaticsSeminar ”Effiziente Programmierung in C”, December, 20121 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?What is OOP?2 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?What is OOP?- programming paradigm2 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?What is OOP?- programming paradigm- sets of common features (attributes)2 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?What is OOP?- programming paradigm- sets of common features (attributes) classes2 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?What is OOP?- programming paradigm- sets of common features (attributes) classes- particular instances of classes2 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?What is OOP?- programming paradigm- sets of common features (attributes) classes- particular instances of classes objects2 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?What is OOP?- programming paradigm- sets of common features (attributes) classes- particular instances of classes objects- manipulating objects2 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?What is OOP?- programming paradigm- sets of common features (attributes) classes- particular instances of classes objects- manipulating objects methods2 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?Can OOP be achieved using only ANSI-C code?3 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?Can OOP be achieved using only ANSI-C code?- yes.3 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?Can OOP be achieved using only ANSI-C code?- yes.- paradigm vs. language feature3 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?Can OOP be achieved using only ANSI-C code?- yes.- paradigm vs. language feature- OO-languages (C , Java, Python etc.)3 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?Can OOP be achieved using only ANSI-C code?- yes.- paradigm vs. language feature- OO-languages (C , Java, Python etc.) offer syntacticsugar to achieve OO-code3 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?Can OOP be achieved using only ANSI-C code?- yes.- paradigm vs. language feature- OO-languages (C , Java, Python etc.) offer syntacticsugar to achieve OO-codeC codeobject- method(some args);3 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?Can OOP be achieved using only ANSI-C code?- yes.- paradigm vs. language feature- OO-languages (C , Java, Python etc.) offer syntacticsugar to achieve OO-codeC codeobject- method(some args);C codemethod(object, some args);3 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?How can it be done?4 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?How can it be done?- with structs,4 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?How can it be done?- with structs, pointers4 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsCan it be done?How can it be done?- with structs, pointers and other wonderful things4 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?What is OOP good for?5 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?What is OOP good for?- data representation and functionality separated from usage5 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?What is OOP good for?- data representation and functionality separated from usage- divide and conquer5 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?What is OOP good for?- data representation and functionality separated from usage- divide and conquer- re-use of code5 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?What is OOP good for?- data representation and functionality separated from usage- divide and conquer- re-use of code- enhanced code readibility5 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?Why should I use C in my program?6 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?Why should I use C in my program?- mostly because it’s faster6 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?Why should I use C in my program?- mostly because it’s faster- environment where C or other compilers not available6 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?Why should I use C in my program?- mostly because it’s faster- environment where C or other compilers not available- you just like it.6 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?Are there any disadvantages with this approach?7 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?Are there any disadvantages with this approach?- rather complex code7 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?Are there any disadvantages with this approach?- rather complex code- possible loss of type safety7 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?Are there any disadvantages with this approach?- rather complex code- possible loss of type safety- programmer time7 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?Are there any disadvantages with this approach?- rather complex code- possible loss of type safety- programmer time- error prone7 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsWhy do it?Are there any disadvantages with this approach?- rather complex code- possible loss of type safety- programmer time- error prone- manual memory management7 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsClasses, objects, methods, constructors and destructorsListing 1: C class example12345678910111213// includes and stuffclass Rectangle {private :int x , y ;int width ;int height ;public :// getters , setters , ifneededvoid draw () ;};void Rectangle :: draw () {std :: cout " Just drew anice " width " by" height "rectangle at position( " x " , " y ")!";}Listing 2: C class example12345678// includes and stufftypedef struct Rectangle {int x , y ;int width ;int height ;} Rectangle ;void draw ( Rectangle * obj ) {printf ( " I just drew a nice% d by % d rectangle atposition (% d , % d ) ! " ,obj - width ,obj - height , obj - x ,obj - y ) ;9 }8 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsClasses, objects, methods, constructors and destructorsListing 3: C object example1 // pretend that everything wealready wrote is here2 // and create an object whereneeded3 Rectangle * r newRectangle () ;Listing 4: C object example1 // pretend that everything wealready wrote is here2 // and create an object whereneeded3 Rectangle * r ( Rectangle *) malloc ( sizeofRectangle ) ;9 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsClasses, objects, methods, constructors and destructorsListing 5: C methods example1 // again , previously definedstuff is here , even ifyou cannot see it !2 void Rectangle :: draw () {3std :: cout " Just drew anice " width " by" height "rectangle at position( " x " , " y ")!";4 }5 // create a Rectangle object6 Rectangle * r newRectangle () ;7 // then just call one if itsmethods8 r - draw () ;Listing 6: C methods example1 // again , previously definedstuff is here , even ifyou cannot see it !2 void draw ( Rectangle * obj ) {3printf ( " I just drew a nice% d by % d rectangle atposition (% d , % d ) ! " ,obj - width ,obj - height , obj - x ,obj - y ) ;4 }5 // create a Rectangle object6 Rectangle * r ( Rectangle *) malloc ( sizeof* Rectangle ) ;7 // then just call a functionthat receives it as aparam8 draw ( r ) ;10 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsClasses, objects, methods, constructors and destructorsListing 8: C constructor exampleListing 7: C constructor example1 // previously defined stuff ishere , as usual2 Rectangle :: Rectangle ( intinitx , int inity , intinitw , int inith ) {3x initx ;4y inity ;5width initw ;6height inith ;7 }8 // and this is how you woulduse it9 Rectangle * r newRectangle (1 ,2 ,3 ,4) ;1 // previously defined stuff ishere , as usual2 Rectangle * Rectan gle init ( intinitx , int inity , intinitw , int inith ) {3struct Rectangle * obj malloc ( sizeof * obj ) ;4obj - x initx ;5obj - y inity ;6obj - width initw ;7obj - height inith ;89return obj ;10 }11 // and this is how you woulduse it12 Rectangle * r Rect angle in it (1 ,2 ,3 ,4) ;11 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsClasses, objects, methods, constructors and destructorsAbout destructors in C Rectangle();-implicitly defined and calledwhen the object is no longerneeded-can be defined explicitly andmanually called if needed12 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsClasses, objects, methods, constructors and destructorsAbout destructors in C Rectangle();-implicitly defined and calledwhen the object is no longerneeded-can be defined explicitly andmanually called if neededAbout destructors in C- there is no automatic memorymanagement in C- you should use free() or wrapyour own function around it- manually call it when needed12 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsEncapsulation- object data is contained and hidden inside of the object- acces to data is restricted to members of that class or otherparticular classes- organising code so that operations on an object type are close tothe definition of that type- lowers the possibility of a user messing up- reduces the amount of details needed to know when trying to usea type- provides decoupling: usage is separated from implementation13 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsEncapsulationAbout encapsulation in C - offers some syntatic sugar tohelp achieve encapsulation- public, protected, private- this is checked by the compiler(at compile time)- you can stab the compiler inthe back and do what you wantto the code at run time anyway14 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsEncapsulationAbout encapsulation in C - offers some syntatic sugar tohelp achieve encapsulation- public, protected, private- this is checked by the compiler(at compile time)- you can stab the compiler inthe back and do what you wantto the code at run time anywayAbout encapsulation in C- C does not offer the samesyntatic sugar- use naming conventions to helpassociate types with theirmethods- integrate functions into structsusing function pointers- private variables vs. privatemethods- also keep in mind that pointersto structs can be used withoutknowledge of the structdeclaration14 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsInheritance- captures the ”is-a” relationship- a pointer to a derived class is type-compatible with a pointer toits base class- i.e. Rectangle ”is-a” Shape- Rectangle inherits properties from Shape- this allows code re-use and a better structure for your program15 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsInheritanceListing 9: C inheritance example1 class Shape {2/* Shape class members */3 };4 class Rectangle : publicShape {5/* Rectangle class members*/6 };Listing 10: C inheritance example1 struct Shape {2/* base class members */3 };4 struct Rectangle {5struct Shape super ;6/* derived class members*/7 };16 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsPolymorphism- allows values of different data types to be handled using anuniform interface- a polymorphic function can be evaluated or applied to values ofdifferent types- polymoprhism takes advantage of inheritance17 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsPolymorphismListing 11: C polymorphism example1234567891011121314151617class Shape { // abstract interfacepublic :virtual void draw () 0; // pure virtual function};class Rectangle : public Shape { // inheritance// other stuff here too of coursepublic :virtual void draw () ; // implement this along the way};// some function that handles a shape p ol y mo rp hi c al lyvoid handleShape ( Shape * s ) {s - draw () ; // then do something to the shape}// usageShape * shape ;shape new Rectangle () ;handleShape ( s ) ;18 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsListing 12: C OOP full example123456789# include iostream /* Shape abstract interface */class Shape {public :virtual void draw () 0;virtual void moveTo ( int newx , int newy ) 0;};19 / 36

Introduction and OOP features and conceptsQuick applicationConclusions/* Rectangle class */class Rectangle : public Shape {private :int x , y ;int width ;int height ;public :Rectangle ( int initx , int inity , int initw , int inith ) ;int getX () { return this - x ; }int getY () { return this - y ; }int getWidth () { return this - width ; }int getHeight () { return this - height ; }void setX ( int newx ) { this - x newx ; }void setY ( int newy ) { this - y newy ; }void setWidth ( int neww ) { this - width neww ; }void setHeight ( int newh ) { this - height newh ; }virtual void draw () ;virtual void moveTo ( int newx , int newy ) ;};20 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusions30 Rectangle :: Rectangle ( int initx , int inity , int initw , intinith ) {31x initx ;32y inity ;33width initw ;34height inith ;35 }3637 void Rectangle :: draw () {38std :: cout " Just drew a nice " width39 " by " height40 " rectangle at position ( " x41 " , " y " ) ! " std :: endl ;42 }4344 void Rectangle :: moveTo ( int newx , int newy ) {45x newx ;46y newy ;47std :: cout " Moving your rectangle to ( " x48 " , " y " ) ! " std :: endl ;49 }21 / 36

Introduction and motivation50515253545556575859606162636465OOP features and conceptsQuick applicationConclusions/* Circle class */class Circle : public Shape {private :int x , y ;int radius ;public :Circle ( int initx , int inity , int initr ) ;virtual void draw () ;virtual void moveTo ( int newx , int newy ) ;int getX () { return this - x ; }int getY () { return this - y ; }int getRadius () { return this - radius ; }void setX ( int newx ) { this - x newx ; }void setY ( int newy ) { this - y newy ; }void setRadius ( int newr ) { this - radius newr ; }};22 / 36

Introduction and motivation666768697071727374757677787980818283OOP features and conceptsQuick applicationConclusionsCircle :: Circle ( int initx , int inity , int initr ) {x initx ;y inity ;radius initr ;}void Circle :: draw () {std :: cout " Just drew a perfect circle of radius " radius " at position ( " x " , " y " ) ! " std :: endl ;}void Circle :: moveTo ( int newx , int newy ) {x newx ;y newy ;std :: cout " Moving your circle to ( " x " , " y " ) ! " std :: endl ;}23 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusions84 /* A function that uses a Shape p o ly mo rp h ic al ly */8586 void handleShape ( Shape * s ) {87std :: cout " Bad shape ! Go to the corner ! " std :: endl ;88s - moveTo (0 ,0) ;89 }24 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusions90 int main () {91/* using shapes po l ym or ph i ca ll y */9293Shape * shapes [2];94shapes [0] new Rectangle (20 , 12 , 123 , 321) ;95shapes [1] new Circle (21 , 12 , 2012) ;9697for ( int i 0; i 2; i ) {98shapes [ i ] - draw () ;99handleShape ( shapes [ i ]) ;100}101102/* access a specific class function */103104Rectangle * r new Rectangle (1 , 2 , 3 , 4) ;105r - setWidth (5) ;106r - draw () ;107108return 0;109 }25 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsListing 13: C OOP full example1234567891011121314# include stdio .h # include stdlib .h # include assert .h /* Shape abstract interface */struct Shape {struct Shape FuncTab le * funcTable ;};struct Shape FuncTabl e {void (* draw ) ( struct Shape * obj ) ;void (* moveTo ) ( struct Shape * obj , int newx , int newy ) ;void (* destructor ) ( struct Shape * obj ) ;};struct Shape * Shape init () { assert (0) ; }void Shape destroy ( struct Shape * obj ) { }26 / 36

Introduction and motivation1516171819202122232425262728OOP features and conceptsQuick applicationConclusions/* Rectangle class */struct Rectangle {struct Shape super ;int x , y ;int width ;int height ;};void R ectangle draw ( struct Shape * obj ) {struct Rectangle * rdata ( struct Rectangle *) obj ;2930 }printf ( " I just drew a nice % d by % d rectangle at position(% d , % d ) ! \ n " ,rdata - width , rdata - height , rdata - x , rdata - y ) ;27 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusions31 void R e c t a n g l e m o v e T o ( struct Shape * obj , int newx , intnewy ) {32struct Rectangle * rdata ( struct Rectangle *) obj ;3334rdata - x newx ;35rdata - y newy ;3637printf ( " Moving your rectangle to (% d , % d ) \ n " ,38rdata - x , rdata - y ) ;39 }4041 void R e c t a n g l e s e t W i d t h ( struct Shape * obj , int neww ) {42struct Rectangle * rdata ( struct Rectangle *) obj ;4344rdata - width neww ;45 }28 / 36

Introduction and 6667OOP features and conceptsQuick applicationvoid R ec t a n g l e d e s t r o y ( struct Shape * obj ) {Shape destroy ( obj ) ;free ( obj ) ;}struct R e c t a n g l e F u n c T a b l e {struct Shape FuncTabl e super ;void (* setWidth ) ( struct Shape * obj , int neww ) ;} r e c t an g l e F u n c T a b l e { {Rectangle draw ,Rectangle moveTo ,Rectangle destroy },Rectangle setWidth};struct Shape * Rectang le init ( int initx , int inity , intinitw , int inith ) {struct Rectangle * obj ( struct Rectangle *)malloc ( sizeof ( struct Rectangle ) ) ;obj - super . funcTable ( struct ShapeFu ncTable *)& rectangleFuncTable ;obj - x initx ;obj - y inity ;obj - width initw ;obj - height inith ;return ( struct Shape *) obj ;}Conclusions29 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusions686970717273747576/* Circle class */struct Circle {struct Shape super ;int x , y ;int radius ;};void Circle draw ( struct Shape * obj ) {struct Circle * cdata ( struct Circle *) obj ;printf ( " Just drew a perfect circle of radius % d atposition (% d , % d ) !\ n " ,77cdata - radius , cdata - x , cdata - y ) ;78 }7980 void Circle moveTo ( struct Shape * obj , int newx , int newy ) {81struct Circle * cdata ( struct Circle *) obj ;82cdata - x newx ;83cdata - y newy ;84printf ( " Moving your circle to (% d , % d ) \ n " ,85cdata - x , cdata - y ) ;86 }30 / 36

Introduction and 4105OOP features and conceptsQuick applicationConclusionsvoid C ircle de stroy ( struct Shape * obj ) {Shape destroy ( obj ) ;free ( obj ) ;}struct C ir c le Fu nc T ab le {struct Shape FuncTabl e super ;} c ir c le Fu nc T ab le { {Circle draw ,Circle moveTo ,Circle dest roy }};struct Shape * Circle init ( int initx , int inity , int initr ) {struct Circle * obj ( struct Circle *)malloc ( sizeof ( struct Circle ) ) ;obj - super . funcTable ( struct ShapeFun cTable *)& ci rc l eF un cT a bl e ;obj - x initx ;obj - y inity ;obj - radius initr ;return ( struct Shape *) obj ;}31 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusions106 # define Shape DRAW ( obj ) ((( structShape *) ( obj ) ) - funcTable - draw (( obj ) ) )107 # define Shape MOVETO ( obj , newx , newy ) \108((( struct Shape *) ( obj ) ) - funcTable - moveTo (( obj ) , ( newx ) ,( newy ) ) )109110 # define R e c t a n g l e S E T W I D T H ( obj , width ) \111(( struct R e c t a n g l e F u n c T a b l e *) (( structShape *) ( obj ) ) - funcTable ) - setWidth ( \112( obj ) , ( width ) )113114 # define Shape DESTROY ( obj ) ((( structShape *) ( obj ) ) - funcTable - destructor (( obj ) ) )115 /* A function that uses a Shape p o ly mo rp h ic al ly */116 void handleShape ( struct Shape * s ) {117Shape MOVETO (s , 0 , 0) ;118 }32 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusions119 int main () {120int i ;121struct Shape * shapes [2];122struct Shape * r ;123/* using shapes po l ym or ph i ca ll y */124shapes [0] Rec tangle i nit (20 ,12 ,123 ,321) ;125shapes [1] Circle init (21 ,12 ,2012) ;126for ( i 0; i 2; i )127{128Shape DRAW ( shapes [ i ]) ;129handleShape ( shapes [ i ]) ;130}131/* accessing Rectangle specific data */132r Rectangl e init (1 , 2 , 3 , 4) ;133R e c t a n g l e S E T W I D T H (r , 5) ;134Shape DRAW ( r ) ;135Shape DESTROY ( r ) ;136137for ( i 1; i 0; --i )138Shape DESTROY ( shapes [ i ]) ;139 }33 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsOOC vs. CPros- better, more logical structuringof code- decoupling: separatingimplementation from usage- code recycling34 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsOOC vs. CPros- better, more logical structuringof code- decoupling: separatingimplementation from usage- code recyclingCons- requires in-depth programmingknowledge- code is more complex andharder to write- manual memory management(manual *everything* actually.)- no syntatic sugar to help writeOO-code more lines of code more time34 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsFurther reading- Object Oriented Programming with ANSI C, by Axel-TobiasSchreiner (free ebook)- Google is your friend35 / 36

Introduction and motivationOOP features and conceptsQuick applicationConclusionsThank you!Thank you for not falling asleep!Any questions?36 / 36

Introduction and motivation OOP features and conceptsQuick application Conclusions Object Oriented Programming in C Radu Grigoras radu.grigoras10@gmail.com University of Hamburg Faculty of Mathematics, Informatics and Natural Sciences Department of Informatics Se