Talk:Classes: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
(→‎The point of the C code?: Some RC-specific perspective)
 
(13 intermediate revisions by 8 users not shown)
Line 1: Line 1:
The task here is not specific enough. The task should an object that does something very simple, for example, a person which has a first name and last name and a method to return full name or a shape returning its area, etc.
[http://thelastprincess.ifrance.com/text/danzel-pum/ danzel pum it] [http://ulyana49.ifrance.com/library/karaoke-nannini.htm karaoke nannini i maschi] [http://littlleru.ifrance.com/blog/cercasi-un/ cercasi un colpevole disperatamente] [http://pantera0511.ifrance.com/lib/konica-minolta2/ konica minolta x60] [http://listtlector.ifrance.com/daniela-mercury.htm daniela mercury] [http://svetljakova.ifrance.com/text/bluetooth-mini.html bluetooth mini keyboard] [http://neverminda.ifrance.com/styles/canon-10.html canon ef 2485 3 54 5 usm] [http://yulechka2004.ifrance.com/new/televisore-4.htm televisore 32 lcd] [http://orangejuls.ifrance.com/view/ostaggio-americano/ ostaggio americano video decapitazione] [http://littlleru.ifrance.com/blog/ht/ ht 51] [http://liieeto.ifrance.com/lib/posizioni-sessuali/ posizioni sessuali] [http://thelastprincess.ifrance.com/text/agricoltura-/ agricoltura servizi] [http://yulechka2004.ifrance.com/new/finanza-dimpresa.htm finanza dimpresa] [http://meterwebdesign.ifrance.com/resources/settlers-heritage.htm settlers heritage of kings] [http://listtlector.ifrance.com/il-testo1.htm il testo della canzone achi mi dice] [http://liieeto.ifrance.com/lib/ferrari-immagine/ ferrari immagine] [http://littlleru.ifrance.com/blog/testo-italiano1/ testo italiano this love maroon 5] [http://listtlector.ifrance.com/agenzia-viaggi1.htm agenzia viaggi imperial] [http://pantera0793.ifrance.com/view/simonelli.htm simonelli] [http://yulechka2004.ifrance.com/new/clio-mtv.htm clio mtv] [http://meterwebdesign.ifrance.com/resources/amd.htm amd 64 939 3000] [http://yulechka2004.ifrance.com/new/kolorowe-jarmarki.htm kolorowe jarmarki] [http://yulechka2004.ifrance.com/new/film-in.htm film in anteprima ottobre] [http://thelastprincess.ifrance.com/text/bocchinare-di/ bocchinare di rimini] [http://uptekar.ifrance.com/articles/yarkand.html yarkand] [http://lifefordea.ifrance.com/blog/pioneer-dcs1.html pioneer dcs 535] [http://yurash.ifrance.com/text/hdrhc-hdv/ hdrhc1 hdv 1080i] [http://neverminda.ifrance.com/styles/giochi-per10.html giochi per sony psp] [http://pantera0793.ifrance.com/view/xxl-.htm x800xl 256 agp] [http://listtlector.ifrance.com/kat-woman.htm kat woman] [http://pantera0511.ifrance.com/lib/viene-da/ viene da me] [http://listtlector.ifrance.com/guardastelle-bungaro.htm guardastelle bungaro] [http://orangejuls.ifrance.com/view/is-it/ is it cos i am cool] [http://yulechka2004.ifrance.com/new/stefan-zweig.htm stefan zweig] [http://thelastprincess.ifrance.com/text/crt-tco/ crt tco99] [http://pantera0793.ifrance.com/view/rodolfo-gaytan.htm rodolfo gaytan castro] [http://orangejuls.ifrance.com/view/dragon-ballz/ dragon ballz] [http://olgasht.ifrance.com/blog/obiettivo-nikon1/ obiettivo nikon d70] [http://pantera0511.ifrance.com/lib/silhouette-palestra/ silhouette palestra bologna] [http://littlleru.ifrance.com/blog/modellismo-r/ modellismo r c] [http://uptekar.ifrance.com/articles/plextor-pxuf.html plextor px716uf] [http://lazurdragon.ifrance.com/html/base-musicale2.htm base musicale renga] [http://lelya50.ifrance.com/new/palmare-con2/ palmare con cellulare videocamera] [http://lelya50.ifrance.com/new/sparami/ sparami] [http://thelastprincess.ifrance.com/text/shadow-of1/ shadow of the colossus prima in usa] [http://lelya50.ifrance.com/new/a-d/ a d a] [http://orangejuls.ifrance.com/view/delonghi-magnifica/ delonghi magnifica] [http://listtlector.ifrance.com/televisori-sharp.htm televisori sharp sintonizzatore digitale] [http://orangejuls.ifrance.com/view/mat-s/ mat s rock the drum] [http://liieeto.ifrance.com/lib/legge3/ legge 40 2004] [http://pantera0511.ifrance.com/lib/sexy-lingerie/ sexy lingerie] [http://ulyana49.ifrance.com/library/tracolla-per.htm tracolla per chitarra] [http://elinaca.ifrance.com/library/hearts/ hearts] [http://neverminda.ifrance.com/styles/trova-il.html trova il testo di where is the love] [http://orangejuls.ifrance.com/view/nooki/ nooki] [http://neverminda.ifrance.com/styles/merceologia.html merceologia] [http://elinaca.ifrance.com/library/www-yahoo/ www yahoo it] [http://lazurdragon.ifrance.com/html/convertitore-wma1.htm convertitore wma in mp3] [http://lelya50.ifrance.com/new/bella-bimba/ bella bimba canzone] [http://lifefordea.ifrance.com/blog/crack-psp.html crack psp] [http://lazurdragon.ifrance.com/html/midi-baciami.htm midi baciami meneguzzi] [http://pantera0793.ifrance.com/view/omosessuali-nudi.htm omosessuali nudi] [http://ulyana49.ifrance.com/library/nastri-magnetici.htm nastri magnetici per computers] [http://lifefordea.ifrance.com/blog/magnum-algida.html magnum algida] [http://orangejuls.ifrance.com/view/sp-problemi/ sp2 problemi messenger] [http://pantera0511.ifrance.com/lib/carmen-duran/ carmen duran] [http://littlleru.ifrance.com/blog/home-theater1/ home theater divx sony] [http://uptekar.ifrance.com/articles/humur.html humur] [http://lifefordea.ifrance.com/blog/mouse-tastiera.html mouse tastiera microsoft] [http://lol89.ifrance.com/topic/el-lady/ el lady com] [http://yurash.ifrance.com/text/hotel-in1/ hotel in tunisia] [http://lazurdragon.ifrance.com/html/uragano-ai.htm uragano ai tropici] [http://neverminda.ifrance.com/styles/martignano-lago.html martignano lago di] [http://olgasht.ifrance.com/blog/inventiamo-lamore/ inventiamo lamore] [http://elinaca.ifrance.com/library/fontainemore/ fontainemore] [http://pantera0793.ifrance.com/view/hechos-tv.htm hechos tv] [http://littlleru.ifrance.com/blog/picnic-in/ picnic in africa] [http://pantera0511.ifrance.com/lib/immagini-e1/ immagini e artwork da phantom kingdom] [http://listtlector.ifrance.com/she-s.htm she s one di r kelly] [http://liieeto.ifrance.com/lib/morticia/ morticia] [http://elinaca.ifrance.com/library/stefania-torretta/ stefania torretta] [http://lifefordea.ifrance.com/blog/bdsm-gallery.html bdsm gallery] [http://lol89.ifrance.com/topic/machomen/ machomen] [http://neverminda.ifrance.com/styles/per-grazia.html per grazia ricevuta] [http://yurash.ifrance.com/text/chitarra-suona/ chitarra suona] [http://olgasht.ifrance.com/blog/venuta/ venuta] [http://listtlector.ifrance.com/ho-letto.htm ho letto] [http://uptekar.ifrance.com/articles/dancing-at.html dancing at the blue iguana] [http://lazurdragon.ifrance.com/html/www-alleanza.htm www alleanza it] [http://lifefordea.ifrance.com/blog/star-comic.html star comic] [http://lazurdragon.ifrance.com/html/negozi-abbigliament.htm negozi abbigliament] [http://lazurdragon.ifrance.com/html/letz-en.htm letz en go1] [http://thelastprincess.ifrance.com/text/octopus-hoover/ octopus hoover] [http://liieeto.ifrance.com/lib/non-piu/ non piu andrai farfallone amoroso] [http://pantera0793.ifrance.com/view/teens-fuck.htm teens fuck] [http://meterwebdesign.ifrance.com/resources/foto-uva.htm foto uva] [http://littlleru.ifrance.com/blog/assicurazione-rieti/ assicurazione rieti] [http://liieeto.ifrance.com/lib/ufficio-forte/ ufficio forte dei marmo] [http://lelya50.ifrance.com/new/la-trappola/ la trappola mortale] [http://listtlector.ifrance.com/aptenodytes.htm aptenodytes] [http://waggie.qiye.in/library/brano-ave.htm brano ave maria di schubert] [http://newssrss.profil.ms/description/stampante-per9/ stampante per dos] [http://angelipravosu.profil.in/text/www-professoresse.html www professoresse in calore it] [http://waggie.qiye.in/library/danna-paola.htm danna paola] [http://dartf.jushige.cn/new/olympus-umini1/ olympus umini digital s] [http://dartf.jushige.cn/new/torta-delle/ torta delle rose] [http://angelipravosu.profil.in/text/eric-pridy.html eric pridy] [http://angelipravosu.profil.in/text/i-tre23.html i tre porcellini] [http://ledstervab.profil.bz/view/www-vear.html www vear it] [http://mikevinogradov.indo.tc/web/ai-ching.htm ai ching] [http://newssrss.profil.ms/description/quadro-fx10/ quadro fx 1100] [http://natysia91.max.io/topic/yahoo-musica/ yahoo musica] [http://matto.jushige.com/new/un-gram/ un gram de iubire] [http://waggie.qiye.in/library/labirinth.htm labirinth] [http://angelipravosu.profil.in/text/www-assicurazioni1.html www assicurazioni com] [http://tohobangleader.ide.am/description/oops-eroare.html oops eroare] [http://waggie.qiye.in/library/s20.htm s] [http://catdog2007.ourprofile.net/data/mas-que5/ mas que tu amigo] [http://angelipravosu.profil.in/text/philips-pw6.html philips 32pw8620 12] [http://ledstervab.profil.bz/view/tsh-pioneer.html tsh1703 pioneer] [http://waggie.qiye.in/library/aspire15.htm aspire 1673] [http://catdog2007.ourprofile.net/data/schettini-pirro/ schettini pirro] [http://newssrss.profil.ms/description/joe-dassin/ joe dassin salut] [http://matto.jushige.com/new/primo-peccato/ primo peccato] [http://tohobangleader.ide.am/description/digitale-terrestre58.html digitale terrestre scheda pc] [http://dartf.jushige.cn/new/listini-agosto/ listini agosto 2004] [http://newssrss.profil.ms/description/fim-/ fim srl] [http://tohobangleader.ide.am/description/colucci-mario.html colucci mario] [http://matto.jushige.com/new/ti-mene1/ ti mene nevolis] [http://tohobangleader.ide.am/description/jt2.html jt 359] [http://matto.jushige.com/new/mitocondria/ mitocondria] [http://dartf.jushige.cn/new/sibel-kekili1/ sibel kekili porno movies] [http://newssrss.profil.ms/description/veramente-mid/ veramente mid] [http://angelipravosu.profil.in/text/pdfdoc.html pdf2doc] [http://tohobangleader.ide.am/description/manometri-tuning.html manometri tuning] [http://waggie.qiye.in/library/nokia83.htm nokia 5140] [http://natysia91.max.io/topic/cantanti-c/ cantanti c] [http://natysia91.max.io/topic/hurricane-polimar2/ hurricane polimar vol 02] [http://angelipravosu.profil.in/text/elton-john13.html elton john interview] [http://angelipravosu.profil.in/text/lupin-anche.html lupin anche su gamecube] [http://catdog2007.ourprofile.net/data/vallelunga/ vallelunga] [http://mikevinogradov.indo.tc/web/kill-puff.htm kill puff daddy] [http://matto.jushige.com/new/guns-n15/ guns n roses slash] [http://tohobangleader.ide.am/description/power-gym3.html power gym 5000 turner] [http://dartf.jushige.cn/new/www-peternorth/ www peternorth com] [http://waggie.qiye.in/library/olympus-6.htm olympus 480 c] [http://matto.jushige.com/new/toner-panasonic5/ toner panasonic kx fl501] [http://catdog2007.ourprofile.net/data/www-la30/ www la cuarta cl] [http://waggie.qiye.in/library/hostels-milan.htm hostels milan] [http://newssrss.profil.ms/description/something-people/ something people] [http://dartf.jushige.cn/new/plastificatrice-a/ plastificatrice a4] [http://mikevinogradov.indo.tc/web/palmare-cellulare3.htm palmare cellulare asus] [http://dartf.jushige.cn/new/troie-sicili/ troie sicili] [http://newssrss.profil.ms/description/panca-pettorali1/ panca pettorali e addominali] [http://newssrss.profil.ms/description/dual-sim2/ dual sim adattatore] [http://matto.jushige.com/new/optical-cavo/ optical cavo] [http://mikevinogradov.indo.tc/web/videoguard.htm videoguard] [http://angelipravosu.profil.in/text/apache-territory.html apache territory] [http://waggie.qiye.in/library/joystick-saitek1.htm joystick saitek force] [http://matto.jushige.com/new/western-digital58/ western digital media center 250gb] [http://angelipravosu.profil.in/text/grundig-.html grundig 3400 mp3] [http://catdog2007.ourprofile.net/data/www-inculate/ www inculate it] [http://tohobangleader.ide.am/description/ja-rule6.html ja rule ashanti feat r kelly wonderful] [http://ledstervab.profil.bz/view/sesso-tra6.html sesso tra calciatori] [http://matto.jushige.com/new/farina-di3/ farina di mais] [http://natysia91.max.io/topic/casa-slim/ casa slim] [http://newssrss.profil.ms/description/www-gucci2/ www gucci it] [http://angelipravosu.profil.in/text/palmari-gsm3.html palmari gsm asus] [http://tohobangleader.ide.am/description/redio-head.html redio head] [http://mikevinogradov.indo.tc/web/asus-a25.htm asus a620 accessori gps] [http://newssrss.profil.ms/description/nike-terminator/ nike terminator] [http://waggie.qiye.in/library/km-hyundai8.htm km0 hyundai accent benzina auto km 0] [http://newssrss.profil.ms/description/hyde-park1/ hyde park hotel] [http://dartf.jushige.cn/new/dentale-sostantivo/ dentale (sostantivo)] [http://tohobangleader.ide.am/description/skiman.html skiman] [http://dartf.jushige.cn/new/www-avril2/ www avril lavigne it] [http://angelipravosu.profil.in/text/lettere-moderne.html lettere moderne] [http://catdog2007.ourprofile.net/data/monitor-philips23/ monitor philips 170s6fg] [http://natysia91.max.io/topic/possibili-argomenti/ possibili argomenti esame di stato 2004] [http://newssrss.profil.ms/description/www-annovi/ www annovi] [http://angelipravosu.profil.in/text/marano-ticino.html marano ticino] [http://mikevinogradov.indo.tc/web/drivers-lg.htm drivers lg u8120] [http://angelipravosu.profil.in/text/guendalina1.html guendalina] [http://natysia91.max.io/topic/dvd-recorder99/ dvd recorder hdmi] [http://newssrss.profil.ms/description/cerco-lavoro23/ cerco lavoro a milano] [http://mikevinogradov.indo.tc/web/radetzky-march1.htm radetzky march] [http://tohobangleader.ide.am/description/tempi.html tempi] [http://natysia91.max.io/topic/b-c3/ b c noleggio auto] [http://catdog2007.ourprofile.net/data/masterizzatori-dvd42/ masterizzatori dvd double layer] [http://newssrss.profil.ms/description/sean-paul11/ sean paul and sasha] [http://tohobangleader.ide.am/description/los-lobos7.html los lobos mariachi] [http://waggie.qiye.in/library/panasonic-tx8.htm panasonic tx 32] [http://ledstervab.profil.bz/view/conquistare-una.html conquistare una donna] [http://angelipravosu.profil.in/text/lyra-pdp.html lyra pdp] [http://newssrss.profil.ms/description/bandi-e1/ bandi e concorsi universita basilicata] [http://catdog2007.ourprofile.net/data/acqua-panna/ acqua panna] [http://natysia91.max.io/topic/pianoforte/ pianoforte] [http://matto.jushige.com/new/download-video15/ download video codec dx 50] [http://ledstervab.profil.bz/view/lombardia-piantina.html lombardia piantina] [http://angelipravosu.profil.in/text/hp-officejet35.html hp officejet psc 1610] The task here is not specific enough. The task should an object that does something very simple, for example, a person which has a first name and last name and a method to return full name or a shape returning its area, etc.
:I think it still works. Adding comments is simple enough for explanation. --[[User:Mwn3d|Mwn3d]] 16:45, 9 March 2009 (UTC)

==Destructor==
What do you guys think about adding a destructor requirement where appropriate? --[[User:Mwn3d|Mwn3d]] 16:45, 9 March 2009 (UTC)
: I think it's a good idea to show, but not worth putting as a requirement. —[[User:Dkf|Donal Fellows]] 09:09, 3 September 2009 (UTC)

== Classes as Objects ==

Some object systems have classes as being entities in the object system: there's a class of classes. Others do not. Is this worth mentioning here (possibly with a link to a task to show what's going on)? (Also, some of the object systems that have a class of classes also allow subclassing of that class...) —[[User:Dkf|Donal Fellows]] 09:12, 3 September 2009 (UTC)

== The point of the C code? ==

Isn't the C sample here a bit useless? After all this work, one ends up with a blob of data, a few functions intended to operator on said data, a lot of ugly long identifiers but no way to do inheritance or polymorphism, because nothing is provided for method dispatching base on type or object. Where's the OO in this? --[[User:Ledrug|Ledrug]] 22:00, 19 June 2011 (UTC)
: When I read the task, the requirements boil down to this sentence: "The purpose of this task is to create a basic class with a method, a constructor, an instance variable and how to instantiate it. ". It appears to only cover encapsulation, not polymorphism or inheritance. There's nothing in there about polymorphism or dispatching based on type. However, I think it may be perfectly appropriate to create multiple tasks, one to an aspect of OO, and deprecate this task in favor of them. That's likely to produce far better results. --[[User:Short Circuit|Michael Mol]] 10:30, 20 June 2011 (UTC)
: While C isn't OO, it can be used to create class-like things. If you stick some function pointers in a struct, it can start to act like a rudimentary class from any number of OO languages. With some work, one struct could also "inherit" from another by copying function pointers and data out of one class and into a second. While none of this would happen automatically, it could be made to happen. Consider:
<lang c>#include <stdio.h>
#include <malloc.h>

struct foo{
int some_int;
void (*new)(struct foo *, int);
void (*print)(struct foo *);
void (*clean)(struct foo *);
};

void foo_new( struct foo * self, int a ){
self->some_int = a;
}

void foo_print( struct foo * self ){
printf( "%d\n", self->some_int );
}

void foo_clean( struct foo * self ){
free( self );
}

struct foo * foo(){
struct foo * new = malloc( sizeof( struct foo ) );
new->new = &foo_new;
new->print = &foo_print;
new->clean = &foo_clean;
return new;
}

int main(){
struct foo * bar = foo();

bar->new( bar, 42 );
bar->print( bar );
bar->clean( bar );

return 0;
}</lang>

Now you could use some other "class" (struct + function pointers) to change the function pointers in some instance of struct foo, emulating some very basic polymorphism. While it's not the best practice, some_int could be a pointer, allowing you to put different types of data "in" the struct, allowing the rest of the code to call foo->print while remaining oblivious to what's really there.

Convoluted, sure, but it works and allows for some OO-like programming.

--[[User:Bnlott|Bnlott]] 22:59, 1 July 2011 (UTC)
::Well sort of. For you code to compile, the compiler has to know how to dereference <code>bar->new</code> to begin with, meaning the type is already known, so it's not polymorphism by type. You can change function pointers on each instance, so it is dynamic dispatch per instance at run time. The value of this can be questioned: how is this better than storing relevant attributes in the struct, and let handler functions do different things accordingly? (note: it can be different, I'm just saying you have to think about it before designing such an interface--syntax sugar, if sugar at all, may come with drawbacks). Secondly, things like inheritance is still not supported at language level, if you want to add a new attribute and a new method to bar, the struct definition need to be changed, existing methods need to be type-coerced, you need to do a lot of type casting using them, and code becomes a mess real fast. And because each instance has its own function pointers, when you create a new instance, you now need to remember to copy all of them, at each level of inheritance, in correct order, etc. You main() function may look more "OO" like, but it's not sustainable when you need to extend it. The real question is, if you <i>need</i> OO, why use C? --[[User:Ledrug|Ledrug]] 23:32, 1 July 2011 (UTC)
:::You are correct when you say that this isn't the most convenient thing ever. For this to have anything like true polymorphism, the code will either become messy or dangerous (possibly both). While you are correct that you shouldn't be using C if you really need OO, things like this can make you life easier. Consider a contrived example: you have a DB access layer like Perl's DBI or Java's JDBC. You could have something like:

<pre>struct DB_access{
+ bool:connect()
+ char**:getData()
+ void:disconnect()
}

mysql_connect();
sqlite_connect();
/* etc... */

mysql();
sqlite();

struct DB_access * DB = sqlite();
struct DB_access * DB = mysql();</pre>

The idea behind switching the function pointers around is to avoid the switch/case and if/else blocks that can result from trying to make single functions handle things differently. This hardly gives you access to all of the capabilities that true OO languages provide, but it does allow for many of the OO design principals to be applied in C.

Take this with a large grain of salt; this needs to be done carefully to avoid ending up in data type hell. It certainly shouldn't be used recklessly. Like I said, it's not really OOP, just an imitation that allows for some OO design principals to be applied. --[[User:Bnlott|Bnlott]] 00:12, 2 July 2011 (UTC)

::Yes I understand that. It's just sometimes people get too excited and starts abusing some of these techniques. It roughly goes like this, in order:

::# "Oooh let's make the struct inheritable" -- make struct foo "has-a" struct bar and extra members, typecast struct foo* to struct bar*;
::# "Oooh let's make it run-time polymorph" -- add function pointers to struct bar; function looks like method(bar *, ...) but clunky when used on foo; fine, change prototype to method(void *, ...)
::# "But inheritance is not convenient?" -- inplement some kind of vtbl, a global table storing method pointers, while first member of foo and bar refer to this table;
::# "But foo's vtbl and bar's vtbl should not be the same?" -- make foo's vtbl an inherited form of bar's; change the method lookup method--

::Notice how the problem of polymorphism of foo and bar now includes polymorphism of foo and bar's vtbls, and we have a meta recursion, goto 1, sanity lost. It's not pertinent to the code example or your comments, just some amusing observations. --[[User:Ledrug|Ledrug]] 00:34, 2 July 2011 (UTC)

:::As a general rule of thumb, if you ever find yourself implementing half of language B in language A, just go use language B. :) --[[User:Bnlott|Bnlott]] 01:10, 2 July 2011 (UTC)
::::Sure, given reasonable circumstantial constraints. However, just to drop a bit of RC-specific perspective, seeing how to implement language B in language A ''greatly'' makes understanding that half of language B ''much'' easier for someone more versed in language A. Comparing and demonstrating languages is only part of what RC does; demonstrating tasks through code is another major part. --[[User:Short Circuit|Michael Mol]] 04:11, 2 July 2011 (UTC)

Latest revision as of 04:11, 2 July 2011

The task here is not specific enough. The task should an object that does something very simple, for example, a person which has a first name and last name and a method to return full name or a shape returning its area, etc.

I think it still works. Adding comments is simple enough for explanation. --Mwn3d 16:45, 9 March 2009 (UTC)

Destructor

What do you guys think about adding a destructor requirement where appropriate? --Mwn3d 16:45, 9 March 2009 (UTC)

I think it's a good idea to show, but not worth putting as a requirement. —Donal Fellows 09:09, 3 September 2009 (UTC)

Classes as Objects

Some object systems have classes as being entities in the object system: there's a class of classes. Others do not. Is this worth mentioning here (possibly with a link to a task to show what's going on)? (Also, some of the object systems that have a class of classes also allow subclassing of that class...) —Donal Fellows 09:12, 3 September 2009 (UTC)

The point of the C code?

Isn't the C sample here a bit useless? After all this work, one ends up with a blob of data, a few functions intended to operator on said data, a lot of ugly long identifiers but no way to do inheritance or polymorphism, because nothing is provided for method dispatching base on type or object. Where's the OO in this? --Ledrug 22:00, 19 June 2011 (UTC)

When I read the task, the requirements boil down to this sentence: "The purpose of this task is to create a basic class with a method, a constructor, an instance variable and how to instantiate it. ". It appears to only cover encapsulation, not polymorphism or inheritance. There's nothing in there about polymorphism or dispatching based on type. However, I think it may be perfectly appropriate to create multiple tasks, one to an aspect of OO, and deprecate this task in favor of them. That's likely to produce far better results. --Michael Mol 10:30, 20 June 2011 (UTC)
While C isn't OO, it can be used to create class-like things. If you stick some function pointers in a struct, it can start to act like a rudimentary class from any number of OO languages. With some work, one struct could also "inherit" from another by copying function pointers and data out of one class and into a second. While none of this would happen automatically, it could be made to happen. Consider:

<lang c>#include <stdio.h>

  1. include <malloc.h>

struct foo{

 int some_int;
 void (*new)(struct foo *, int);
 void (*print)(struct foo *);
 void (*clean)(struct foo *);

};

void foo_new( struct foo * self, int a ){

 self->some_int = a;

}

void foo_print( struct foo * self ){

 printf( "%d\n", self->some_int );

}

void foo_clean( struct foo * self ){

 free( self );

}

struct foo * foo(){

 struct foo * new = malloc( sizeof( struct foo ) );
 new->new = &foo_new;
 new->print = &foo_print;
 new->clean = &foo_clean;
 return new;

}

int main(){

 struct foo * bar = foo();
 bar->new( bar, 42 );
 bar->print( bar );
 bar->clean( bar );
 return 0;

}</lang>

Now you could use some other "class" (struct + function pointers) to change the function pointers in some instance of struct foo, emulating some very basic polymorphism. While it's not the best practice, some_int could be a pointer, allowing you to put different types of data "in" the struct, allowing the rest of the code to call foo->print while remaining oblivious to what's really there.

Convoluted, sure, but it works and allows for some OO-like programming.

--Bnlott 22:59, 1 July 2011 (UTC)

Well sort of. For you code to compile, the compiler has to know how to dereference bar->new to begin with, meaning the type is already known, so it's not polymorphism by type. You can change function pointers on each instance, so it is dynamic dispatch per instance at run time. The value of this can be questioned: how is this better than storing relevant attributes in the struct, and let handler functions do different things accordingly? (note: it can be different, I'm just saying you have to think about it before designing such an interface--syntax sugar, if sugar at all, may come with drawbacks). Secondly, things like inheritance is still not supported at language level, if you want to add a new attribute and a new method to bar, the struct definition need to be changed, existing methods need to be type-coerced, you need to do a lot of type casting using them, and code becomes a mess real fast. And because each instance has its own function pointers, when you create a new instance, you now need to remember to copy all of them, at each level of inheritance, in correct order, etc. You main() function may look more "OO" like, but it's not sustainable when you need to extend it. The real question is, if you need OO, why use C? --Ledrug 23:32, 1 July 2011 (UTC)
You are correct when you say that this isn't the most convenient thing ever. For this to have anything like true polymorphism, the code will either become messy or dangerous (possibly both). While you are correct that you shouldn't be using C if you really need OO, things like this can make you life easier. Consider a contrived example: you have a DB access layer like Perl's DBI or Java's JDBC. You could have something like:
struct DB_access{
+ bool:connect()
+ char**:getData()
+ void:disconnect()
}

mysql_connect();
sqlite_connect();
/* etc... */

mysql();
sqlite();

struct DB_access * DB = sqlite();
struct DB_access * DB = mysql();

The idea behind switching the function pointers around is to avoid the switch/case and if/else blocks that can result from trying to make single functions handle things differently. This hardly gives you access to all of the capabilities that true OO languages provide, but it does allow for many of the OO design principals to be applied in C.

Take this with a large grain of salt; this needs to be done carefully to avoid ending up in data type hell. It certainly shouldn't be used recklessly. Like I said, it's not really OOP, just an imitation that allows for some OO design principals to be applied. --Bnlott 00:12, 2 July 2011 (UTC)

Yes I understand that. It's just sometimes people get too excited and starts abusing some of these techniques. It roughly goes like this, in order:
  1. "Oooh let's make the struct inheritable" -- make struct foo "has-a" struct bar and extra members, typecast struct foo* to struct bar*;
  2. "Oooh let's make it run-time polymorph" -- add function pointers to struct bar; function looks like method(bar *, ...) but clunky when used on foo; fine, change prototype to method(void *, ...)
  3. "But inheritance is not convenient?" -- inplement some kind of vtbl, a global table storing method pointers, while first member of foo and bar refer to this table;
  4. "But foo's vtbl and bar's vtbl should not be the same?" -- make foo's vtbl an inherited form of bar's; change the method lookup method--
Notice how the problem of polymorphism of foo and bar now includes polymorphism of foo and bar's vtbls, and we have a meta recursion, goto 1, sanity lost. It's not pertinent to the code example or your comments, just some amusing observations. --Ledrug 00:34, 2 July 2011 (UTC)
As a general rule of thumb, if you ever find yourself implementing half of language B in language A, just go use language B.  :) --Bnlott 01:10, 2 July 2011 (UTC)
Sure, given reasonable circumstantial constraints. However, just to drop a bit of RC-specific perspective, seeing how to implement language B in language A greatly makes understanding that half of language B much easier for someone more versed in language A. Comparing and demonstrating languages is only part of what RC does; demonstrating tasks through code is another major part. --Michael Mol 04:11, 2 July 2011 (UTC)