I had looked at the Stroustrup book a few years back when I knew NOTHING about c++ and it looked too advanced. It just felt more like a manual than explaning concepts. I'll look at it again - Maybe this time will be different. How detailed does it get?
yup the bjarne book is not to be picked up if u don't know a little about C++ already ... it's not a beginners book ... what i like about the guy is that he writes very clearly and he's not tried to explain very damn feature of the language .. it's more like how to use the kowledge u already have effectively .. that i like ... and he is a genius ... and he covers everything ... or nearly everything :) ... not finished the book yet!!
Another book I was wondering if you had looked at was "The Design and Evolution of C++". I think this might be a worthwhile read. It seems quite interesting.
i heard of this one too ... from the reviews i can't decipher whether it is based more on history of C++ rather than it's design .. tell me if u get more info
What kind of philosophy are you talking about? I used to think that I would like philosophy, but I'm taking a "Human Nature" class this sem and it's just awful. Dunno if it's the prof or the material - I just can't stand it.
it's probably both ... one leads to the other ..... what kind of works do they ask u to refer ... immanuel kant or david hume or some dumb bastard on the same lines? .. ayn rand's philosophy is called objectivism ... her philosophy is based on the premise that "A is A" -- that is objective reality ... she potrays man as a hero ... i know ppl will go through thier lives without having thought for a single day about philosophy or morality ... but if u ask me the first thing u should think about is philosophy ... not in the abstract ivory tower way ppl talk about it ... everything u do needs to be based on that philosophy .. take two days off and read her book .. i assure you it will be worth it ... she changed my life :) ... read both ... first fountainhead and then atlas shrugged ..... if ur dad has actually based his company's name on fountainhead .. man i'd like to meet him someday .. i don't meet ppl very often who love her work like i do :)
i wish i could take a philosophy course somewhere but i doubt they teach the kind of stuff i like.
try these links
www.aynrand.org
www.objectivescience.com
www.capitalism.org
dinesh.
Sunday, November 30, 2003
Re: Books
Contrary to what you said Mohn, I think when a function is virtual in a base class, it need not be virtual in all derived classes. If it is defined differently in those derived classes (the base function would get overridden), it would be just a regular non-virtual function of that derived class, right? So I suppose this would also be the answer to your query... to make a function non-virtual in a derived class, just define it there - it would become non-virtual.
As Dinesh already said, if the function is NOT virtual in all derived class objects as well, then the purpose of polymorphism will be lost. I really don't think there is a way to "stop" virtualness in the heirarchy. Once virtual, always virtual in all objects. That's why in C++, the "virtual" keyword is optional in derived classes. Whether or NOT it is present, it is still virtual. I guess for better readability you should make it a point to always include it.
BTW, how the %^ do I 'reply' to the posts?!
Yeah unfortunately, the blog medium is NOT the greatest when it comes to organization. A newgroup/message board would have been better. We could have subject threads and continue each discussion in the appropriate one. Here it is just linear posts. You just have to copy previous message posts and include it in your reply.
Also, just to add to what Dinesh said about the HTML bit. You can just use the color names itself in place of the hex values. So you can say < font color="blue" > instead of < font color="#ff0000" >. Much easier to remember.
C++ books ... i have read lafore, C++ complete reference (Herbert Schildt) ... and right now reading "C++ The Programming Language by Bjarne Stroustrup" .. and the bjarne book is by far one of the best i've read .. it's simply awesome
I had looked at the Stroustrup book a few years back when I knew NOTHING about c++ and it looked too advanced. It just felt more like a manual than explaning concepts. I'll look at it again - Maybe this time will be different. How detailed does it get?
Another book I was wondering if you had looked at was "The Design and Evolution of C++". I think this might be a worthwhile read. It seems quite interesting.
Inside the C++ Object Model by Stanley B. Lippman
i think with the Lippman book i will come close to knowing a lot in C++
Just hopped over to amazon.com and read the reviews. This is EXACTLY what I've been looking for - It explains what lies beneath (Wasn't that a movie?). Just to understand stuff that goes on under the covers. I'm most interested in those kinds of things. Probably not the most useful thing when doing day to day programming, but its just something that could help.
other books on C++ i have seen and which r supposed to be extremely good r
The C++ Standard Library : A Tutorial and Reference by Nicolai M. Josuttis
I have this book. It is NOT too good. It is just more of a reference than anything. And even that is NOT the best. I dunno why it is recommended so highly.
arre yaar main problem is not reading these books ... problem is getting ur hands on them ... books without indian edition r like 2500 ... thats just not affordable ... and it takes too much time for them to come to Indian Edition's
Yeah I know what you mean. I don't buy books. They are just TOO expensive. More often than not you will read them only once. And for reference your best bet will be the net, not a book, since it is more up to date. I just look to libraries and HOPE they will have the book. Somebody should do a Project Gutenberg type thing for tech related books.
One volume of books that I REALLY REALLY want to read before I croak is Donald Knuth's "The Art of Computer Programming". That man is a freakn genius. I've heard SO much about him and his books. If I ever finish this volume I will feel like I have accomplished something in my life.
one thing i haven't read r books which are technology specific .. like the ones u mentioned mohnish ... is it important to read them? .. maybe i should get my hands on the .NET book .. u tell me the pro's and con's :)
I guess it depends on what you like. Rahul and myself tend towards these books cause thats where our interests lie. We are more into web/client app development than game programming/AI. To develop them we need to know what capabilities the platform provides - what libraries/APIs are available to us. I'm sure it's the same with game programming - you got OpenGL and DirectX etc...
ok sorry guys but i had to include this, i'm also a philosophy freak .. try to get ur hands on "Atlas Shrugged" or "The Fountainhead" by Ayn Rand :):) .. totally awesome ..
What kind of philosophy are you talking about? I used to think that I would like philosophy, but I'm taking a "Human Nature" class this sem and it's just awful. Dunno if it's the prof or the material - I just can't stand it.
My dad's company is actually called Fountainhead Solutions. He said he's read "The Fountainhead", but won't tell me if its based off of that or not.
have just seen a few oreilly and wrox titles. wrox might be a little lengthy
I generally prefer Orielly to Wrox. Wrox gets TOO long and they have like a million authors for one book ;-) Orielly is more to the point and sticks to 1-3 authors.
does .net have open community projects?
www.gotdotnet.com is a .NET community site and has "workspaces" where you can join in with open projects.
Saturday, November 29, 2003
Linux Power Utilities - nmap
i'll be writing a bit on some cool linux utilites, the few i come across. i think linux is one thing common between us. ie the wish to learn it really well. hrishi should be able to give us a lot of tips on linux.
here's one cool command line utility
nmap basically scans all the ports of a remote server/pc and provides info on all the open ports etc. you can also get info like whether a server is up.
usage:
$ nmap -v domainname
where -v is for verbose and domainname is the webaddress of a site.
there are many other options. so goto man pages.
on localhost i got
The Connect() Scan took 0 seconds to scan 1601 ports.
Interesting ports on localhost.localdomain (127.0.0.1):
(The 1597 ports scanned but not shown below are in state: closed)
Port State Service
22/tcp open ssh
80/tcp open http
443/tcp open https
6000/tcp open X11
after i started apache(80 and 443) and ssh(22). why x11 is there i do not know. any idea?
i would definitely love to test it on a windows machine.. see you online. and try it on some websites.. really cool.
here's one cool command line utility
nmap basically scans all the ports of a remote server/pc and provides info on all the open ports etc. you can also get info like whether a server is up.
usage:
$ nmap -v domainname
where -v is for verbose and domainname is the webaddress of a site.
there are many other options. so goto man pages.
on localhost i got
The Connect() Scan took 0 seconds to scan 1601 ports.
Interesting ports on localhost.localdomain (127.0.0.1):
(The 1597 ports scanned but not shown below are in state: closed)
Port State Service
22/tcp open ssh
80/tcp open http
443/tcp open https
6000/tcp open X11
after i started apache(80 and 443) and ssh(22). why x11 is there i do not know. any idea?
i would definitely love to test it on a windows machine.. see you online. and try it on some websites.. really cool.
Books..
on design books.. i haven't read any but heard of this one book. Design Patterns - Elements of Reusable Software, by Gamma, Helm, Johnson and Vlissedes. its supposed to be a classic commonly known as Gang of Four - GoF. i actually got a design book, not read a page, which talks of it.
on java books.. i have just seen a few oreilly and wrox titles. wrox might be a little lengthy. there are many books based on many different concepts on java like jsp, ejb's etc.
actually java has a lot of online resources. thats where i get current info, articles etc. http://www.ibm.com/developerworks is one great resource for tutorials, articles etc. they have some some excellent linux stuff also. oreilly has a good artiles section based on topics like http://www.onjava.com. there are also a few open books, like http://www.theserverside.com
you guys ever thought of joining any open/free source projects? one of java's main strengths is a vast online community with a huge number of projects. visit http://www.jakarta.apache.org for one great resource. does .net have open community projects?
on java books.. i have just seen a few oreilly and wrox titles. wrox might be a little lengthy. there are many books based on many different concepts on java like jsp, ejb's etc.
actually java has a lot of online resources. thats where i get current info, articles etc. http://www.ibm.com/developerworks is one great resource for tutorials, articles etc. they have some some excellent linux stuff also. oreilly has a good artiles section based on topics like http://www.onjava.com. there are also a few open books, like http://www.theserverside.com
you guys ever thought of joining any open/free source projects? one of java's main strengths is a vast online community with a huge number of projects. visit http://www.jakarta.apache.org for one great resource. does .net have open community projects?
Re: Books :)
forgot to mention this before ... if anyone is interested in Prolog try ... Prolog Programming for Artificial Intelligence by Ivan Bratko ... i read this book sometime ago .. it's an awesome book :)
dinesh.
dinesh.
Re: Books :)
first hrishi ... i think every virtual function in the base will result in that function being virtual in the derived class ... if u don't want it to be virtual i think the only option u have is make a new function with a different name or create concrete objects in the main code instead of using base pointers .. then u wouldn't be using the virtual function mechanism (i think) ... if u were able to make it non-virtual wouldn't the whole point of polymorphism be lost?
and use < FONT color=#ff0000 > for putting something in red and end it with < /FONT > ... remember to remove the spaces. #00ff00 = blue and #0000ff = green
ok now on to the books ... i have not read any design books either ... but that Modern C++ Design (acc. to the research i did on the net) they say is just awesome.
first i have to say my interests r C++ , Artificial Intelligence and Graphics Programming
C++ books ... i have read lafore, C++ complete reference (Herbert Schildt) ... and right now reading "C++ The Programming Language by Bjarne Stroustrup" .. and the bjarne book is by far one of the best i've read .. it's simply awesome ... books i want to read (but i'm sure never gonna get my hands on) are
Modern C++ Design, Inside the C++ Object Model by Stanley B. Lippman
i think with the Lippman book i will come close to knowing a lot in C++ and the design book ... cause i haven't read any design book before .. and design is very important to development ...... other books on C++ i have seen and which r supposed to be extremely good r
The C++ Standard Library : A Tutorial and Reference by Nicolai M. Josuttis
C++ Templates: The Complete Guide by David Vandevoorde , Nicolai M. Josuttis
i hear the "Effective C++" book series also r very very good ... arre yaar main problem is not reading these books ... problem is getting ur hands on them ... books without indian edition r like 2500 ... thats just not affordable ... and it takes too much time for them to come to Indian Edition's
one thing i haven't read r books which are technology specific .. like the ones u mentioned mohnish ... is it important to read them? .. maybe i should get my hands on the .NET book .. u tell me the pro's and con's :)
ok w.r.t Artificial Intelligence .. there is this book Artificial Intelligence: A Modern Approach (Second Edition) by Stuart Russell and Peter Norvig
this is supposed to be like a bible ... i bought this book a little while ago .. haven't found the time to read it though :)
and general Graphics Programming there is a book by Foley, van Damm which is supposed to be a pioneer in the feild of Computer graphics and w.r.t game engines there is "3D Game Engine Design by David H. Eberly" .. this is also an awesome book .. i have this too ... just read little bit of it ... the ai book and this one r on my todo list for 8th sem :):)
ok sorry guys but i had to include this, i'm also a philosophy freak .. try to get ur hands on "Atlas Shrugged" or "The Fountainhead" by Ayn Rand :):) .. totally awesome ..
ok thats it from me .. i hope i didn't bore ur'll.
adios,
dinesh.
and use < FONT color=#ff0000 > for putting something in red and end it with < /FONT > ... remember to remove the spaces. #00ff00 = blue and #0000ff = green
ok now on to the books ... i have not read any design books either ... but that Modern C++ Design (acc. to the research i did on the net) they say is just awesome.
first i have to say my interests r C++ , Artificial Intelligence and Graphics Programming
C++ books ... i have read lafore, C++ complete reference (Herbert Schildt) ... and right now reading "C++ The Programming Language by Bjarne Stroustrup" .. and the bjarne book is by far one of the best i've read .. it's simply awesome ... books i want to read (but i'm sure never gonna get my hands on) are
Modern C++ Design, Inside the C++ Object Model by Stanley B. Lippman
i think with the Lippman book i will come close to knowing a lot in C++ and the design book ... cause i haven't read any design book before .. and design is very important to development ...... other books on C++ i have seen and which r supposed to be extremely good r
The C++ Standard Library : A Tutorial and Reference by Nicolai M. Josuttis
C++ Templates: The Complete Guide by David Vandevoorde , Nicolai M. Josuttis
i hear the "Effective C++" book series also r very very good ... arre yaar main problem is not reading these books ... problem is getting ur hands on them ... books without indian edition r like 2500 ... thats just not affordable ... and it takes too much time for them to come to Indian Edition's
one thing i haven't read r books which are technology specific .. like the ones u mentioned mohnish ... is it important to read them? .. maybe i should get my hands on the .NET book .. u tell me the pro's and con's :)
ok w.r.t Artificial Intelligence .. there is this book Artificial Intelligence: A Modern Approach (Second Edition) by Stuart Russell and Peter Norvig
this is supposed to be like a bible ... i bought this book a little while ago .. haven't found the time to read it though :)
and general Graphics Programming there is a book by Foley, van Damm which is supposed to be a pioneer in the feild of Computer graphics and w.r.t game engines there is "3D Game Engine Design by David H. Eberly" .. this is also an awesome book .. i have this too ... just read little bit of it ... the ai book and this one r on my todo list for 8th sem :):)
ok sorry guys but i had to include this, i'm also a philosophy freak .. try to get ur hands on "Atlas Shrugged" or "The Fountainhead" by Ayn Rand :):) .. totally awesome ..
ok thats it from me .. i hope i didn't bore ur'll.
adios,
dinesh.
books, polymorphism
First about polymorphism.
Contrary to what you said Mohn, I think when a function is virtual in a base class, it need not be virtual in all derived classes. If it is defined differently in those derived classes (the base function would get overridden), it would be just a regular non-virtual function of that derived class, right? So I suppose this would also be the answer to your query... to make a function non-virtual in a derived class, just define it there - it would become non-virtual.
BTW, how the %^ do I 'reply' to the posts?! As in, what do I do if I want to insert a few lines you guys have written? I still have a few queries about the polymorphism postings and I am finding myself incredibly handicapped and frustrated without the 'reply' thing! :-(
If some html tags have to be put to change colour etc., what are they? I have zot fundaes about html.
Haven't read any language book cover to cover. I picked up C++ from the book by Lafore. It's pretty basic but I thought it illustrates the concepts pretty well. Good to get your started. After that I just started reading shit off google searches. Nothing in particular. google.com is the best way to solve a query, in my opinion! :-)
Has anyone gone through any 'unleashed' books? I haven't read any in detail but they appear to be pretty comprehensive.
One book I really like is 'Unix programming environment' by Kernighan and Pike. Whether you're new to the world of the shell or not, you'd definitely find utility in the book. That's the book you turn to for unix / shell scripting info.
I happened to 'glance' through a couple of books by Donald Knuth on Algorithms. Don't quite remember what the actual title of the book. It comes in volumes. Man, that's HEAVYWEIGHT!
Contrary to what you said Mohn, I think when a function is virtual in a base class, it need not be virtual in all derived classes. If it is defined differently in those derived classes (the base function would get overridden), it would be just a regular non-virtual function of that derived class, right? So I suppose this would also be the answer to your query... to make a function non-virtual in a derived class, just define it there - it would become non-virtual.
BTW, how the %^ do I 'reply' to the posts?! As in, what do I do if I want to insert a few lines you guys have written? I still have a few queries about the polymorphism postings and I am finding myself incredibly handicapped and frustrated without the 'reply' thing! :-(
If some html tags have to be put to change colour etc., what are they? I have zot fundaes about html.
Haven't read any language book cover to cover. I picked up C++ from the book by Lafore. It's pretty basic but I thought it illustrates the concepts pretty well. Good to get your started. After that I just started reading shit off google searches. Nothing in particular. google.com is the best way to solve a query, in my opinion! :-)
Has anyone gone through any 'unleashed' books? I haven't read any in detail but they appear to be pretty comprehensive.
One book I really like is 'Unix programming environment' by Kernighan and Pike. Whether you're new to the world of the shell or not, you'd definitely find utility in the book. That's the book you turn to for unix / shell scripting info.
I happened to 'glance' through a couple of books by Donald Knuth on Algorithms. Don't quite remember what the actual title of the book. It comes in volumes. Man, that's HEAVYWEIGHT!
Re: Books :)
This is a good idea.
I haven't read "Modern C++ Design". I haven't really read design or pattern related books. But I want to. If you could recommend some.
Probably the best "programming language" book I've read is "Thinking in C++" by Bruce Eckel. He does a VERY good job of explaining concepts. You can get it for free from his website actually.... http://mindview.net/Books. There are several other "Thinking" books there.
I have read a lot of technology specific books, which might not really appeal to you. Technologies like MFC, .NET, ASP etc...
I have heard about "Effective C++", "Effective STL", "Exceptional C++" etc... What dyou think of these?
I haven't read "Modern C++ Design". I haven't really read design or pattern related books. But I want to. If you could recommend some.
Probably the best "programming language" book I've read is "Thinking in C++" by Bruce Eckel. He does a VERY good job of explaining concepts. You can get it for free from his website actually.... http://mindview.net/Books. There are several other "Thinking" books there.
I have read a lot of technology specific books, which might not really appeal to you. Technologies like MFC, .NET, ASP etc...
I have heard about "Effective C++", "Effective STL", "Exceptional C++" etc... What dyou think of these?
Books :)
mohnish have u read "Modern C++ Design by Andrei Alexandrescu" .. do u know of any other design books? .. i would like to buy this book .. but it's not in indian edition without which it is too expensive .. so guess i have to wait
hey lets do one thing .. everyone just list out names of books they have read and "really" liked .. books on any programming language or just general software engineering (design ) or just any freakin' book u ever liked .. this would be a good way to know what to read if u plan to that particular thing.
dinesh.
hey lets do one thing .. everyone just list out names of books they have read and "really" liked .. books on any programming language or just general software engineering (design ) or just any freakin' book u ever liked .. this would be a good way to know what to read if u plan to that particular thing.
dinesh.
Friday, November 28, 2003
Re: Polymorphism
i think u forgot that the vector is holding Base* .. so *g will dereference to a Base* .. hence got to use (*g)->pr();
I think it's time for me to get an eye checkup.
Re: Polymorphism
glad u cleared all of that .. thank u :)
This is just a minor thing, but I don't think this is correct...
(*g)->pr()
g is an iterator. An iterator behaves like a pointer. When you dereference an iterator, just like a pointer, you get back an object. So you have to use the dot operator, not the arrow....
(*g).pr();
Like I said, no big deal.
i think u forgot that the vector is holding Base* .. so *g will dereference to a Base* .. hence got to use (*g)->pr();
dinesh.
This is just a minor thing, but I don't think this is correct...
(*g)->pr()
g is an iterator. An iterator behaves like a pointer. When you dereference an iterator, just like a pointer, you get back an object. So you have to use the dot operator, not the arrow....
(*g).pr();
Like I said, no big deal.
i think u forgot that the vector is holding Base* .. so *g will dereference to a Base* .. hence got to use (*g)->pr();
dinesh.
Re: Polymorphism
Some questions which have arised and what I think are the answers...
are u sure about this? ... cause i always thought that the pointer created on the object directly points to the v-table of the class
Right, each object points to its own v-table. This is separate from the base class v-table.
that is if i were to write
Base* ptr;
ptr = new Derv();
ptr->pr();
the object created on the free store would have a pointer to Derv's v-table directly .. so why does it have to look at Base's v-table? for the index?
The object created on the free store ONLY has knowledge of itself. It has no idea that the address returned is going to be stored in a Base class pointer. So it would make sense for that (derived) object to have its own v-table.
In your example Dinesh, only the base class has a virtual function and therefore pr only figures in the v-table of base. pr wouldn't figure in the v-table of derv (if it had one) at all since it's not virtual in derv.
Actually, I believe that if a function is declared virtual in a base class, it is implicitly virtual in ALL derived classes as well, whether or not you declare it virtual. So, in Dinesh's example, pr() is virtual in Derv as well.
I dunno if there is a way in c++ to prevent making a function that is already virtual in a base class, virtual in a derived class. Any idea?
Regardless, ALL classes in that hierarchy will have v-tables. One virtual function is ALL you need.
from "Inside the C++ Object Model" by Stanley Lippman ... the constructor of Derv makes the pointer created in the object point to Derv's v-table .. but the index is calculated using knowledge from Base .. cool :):) .. was this what u were trying to say mohnish? .. what i was confused about was to which v-table does the pointer point to ... well thats that :):)
Yes, this is what I was saying. The function addresses in the v-table will appear in the same index, but there will be DIFFERENT v-table for each derived class object. I just didn't phrase it right.
If you have a base class pointer to a derived class object, you will still have a derived class v-table right? So when you call a method on that base class pointer, it will go to the correct index, since they are the same in both the base and derived v-tables, and call the derived class method.
I am still quite confused about the whole thing. If the pointer points to Derv's v-table, how the hell does it even know of the virtual functions in base? That info would only be contained in base's v-table. So how exactly would the index be calculated from base?
Derived classes don't know about base class virtual functions.
Ok consider this...
class Base
{
virtual void fun() { std::cout << "Base"; }
}
class Derived1 : public Base
{
virtual void fun() { std::cout << "Derived1"; }
}
class Derived2 : public Base
{
}
Base class objects have a v-table with one index. That index, say index 0, has the address of Base's fun(). Derived1 also has a v-table with one index. Index 0 has the address of Derived1's fun(). Now, Derived2 does NOT override Base's fun(). But it also has a v-table with one index. That index has the address of Base's fun(). If a derived class choses NOT to override a virtual function, the index in the v-table will point to the address of the base class function.
So when you do...
Base* p;
p = new Derived1;
p->fun() // goes to Derived1's v-table, index 0, which calls Derived1's fun()
p = new Derived2;
p->fun() // goes to Derived2's v-table, index 0, which calls Base's fun()
These indices are calculated by the compiler at compile time and are implementation dependant. I guess the performance penalty is in the indirection. Instead of going straight to the function, you have to go to a table and then from there go to the function.
for(vector< Base* >::iterator g = ptr.begin(); g != ptr.end(); ++g)
(*g)->pr();
This is just a minor thing, but I don't think this is correct...
(*g)->pr()
g is an iterator. An iterator behaves like a pointer. When you dereference an iterator, just like a pointer, you get back an object. So you have to use the dot operator, not the arrow....
(*g).pr();
Like I said, no big deal.
are u sure about this? ... cause i always thought that the pointer created on the object directly points to the v-table of the class
Right, each object points to its own v-table. This is separate from the base class v-table.
that is if i were to write
Base* ptr;
ptr = new Derv();
ptr->pr();
the object created on the free store would have a pointer to Derv's v-table directly .. so why does it have to look at Base's v-table? for the index?
The object created on the free store ONLY has knowledge of itself. It has no idea that the address returned is going to be stored in a Base class pointer. So it would make sense for that (derived) object to have its own v-table.
In your example Dinesh, only the base class has a virtual function and therefore pr only figures in the v-table of base. pr wouldn't figure in the v-table of derv (if it had one) at all since it's not virtual in derv.
Actually, I believe that if a function is declared virtual in a base class, it is implicitly virtual in ALL derived classes as well, whether or not you declare it virtual. So, in Dinesh's example, pr() is virtual in Derv as well.
I dunno if there is a way in c++ to prevent making a function that is already virtual in a base class, virtual in a derived class. Any idea?
Regardless, ALL classes in that hierarchy will have v-tables. One virtual function is ALL you need.
from "Inside the C++ Object Model" by Stanley Lippman ... the constructor of Derv makes the pointer created in the object point to Derv's v-table .. but the index is calculated using knowledge from Base .. cool :):) .. was this what u were trying to say mohnish? .. what i was confused about was to which v-table does the pointer point to ... well thats that :):)
Yes, this is what I was saying. The function addresses in the v-table will appear in the same index, but there will be DIFFERENT v-table for each derived class object. I just didn't phrase it right.
If you have a base class pointer to a derived class object, you will still have a derived class v-table right? So when you call a method on that base class pointer, it will go to the correct index, since they are the same in both the base and derived v-tables, and call the derived class method.
I am still quite confused about the whole thing. If the pointer points to Derv's v-table, how the hell does it even know of the virtual functions in base? That info would only be contained in base's v-table. So how exactly would the index be calculated from base?
Derived classes don't know about base class virtual functions.
Ok consider this...
class Base
{
virtual void fun() { std::cout << "Base"; }
}
class Derived1 : public Base
{
virtual void fun() { std::cout << "Derived1"; }
}
class Derived2 : public Base
{
}
Base class objects have a v-table with one index. That index, say index 0, has the address of Base's fun(). Derived1 also has a v-table with one index. Index 0 has the address of Derived1's fun(). Now, Derived2 does NOT override Base's fun(). But it also has a v-table with one index. That index has the address of Base's fun(). If a derived class choses NOT to override a virtual function, the index in the v-table will point to the address of the base class function.
So when you do...
Base* p;
p = new Derived1;
p->fun() // goes to Derived1's v-table, index 0, which calls Derived1's fun()
p = new Derived2;
p->fun() // goes to Derived2's v-table, index 0, which calls Base's fun()
These indices are calculated by the compiler at compile time and are implementation dependant. I guess the performance penalty is in the indirection. Instead of going straight to the function, you have to go to a table and then from there go to the function.
for(vector< Base* >::iterator g = ptr.begin(); g != ptr.end(); ++g)
(*g)->pr();
This is just a minor thing, but I don't think this is correct...
(*g)->pr()
g is an iterator. An iterator behaves like a pointer. When you dereference an iterator, just like a pointer, you get back an object. So you have to use the dot operator, not the arrow....
(*g).pr();
Like I said, no big deal.
Re: Polymorphism
I am still quite confused about the whole thing. If the pointer points to Derv's v-table, how the hell does it even know of the virtual functions in base? That info would only be contained in base's v-table. So how exactly would the index be calculated from base?
Coming to your example Dinesh... I haven't actually seen the output but my guess would be Derived and not Derived1 as the last output. If you are saying it exhibits polymorphic behaviour and the output is Derived1, this adds to the confusion. Derv1 is derived from Derv and pr isn't virtual in Derv, then how does the pr in Derv1 get called?!
Heavens... I need a good book on this topic!
Coming to your example Dinesh... I haven't actually seen the output but my guess would be Derived and not Derived1 as the last output. If you are saying it exhibits polymorphic behaviour and the output is Derived1, this adds to the confusion. Derv1 is derived from Derv and pr isn't virtual in Derv, then how does the pr in Derv1 get called?!
Heavens... I need a good book on this topic!
Re: Polymorphism
from "Inside the C++ Object Model" by Stanley Lippman ... the constructor of Derv makes the pointer created in the object point to Derv's v-table .. but the index is calculated using knowledge from Base .. cool :):) .. was this what u were trying to say mohnish? .. what i was confused about was to which v-table does the pointer point to ... well thats that :):)
dinesh.
dinesh.
Thursday, November 27, 2003
Re: Polymorphism
ok .. try this
#include < iostream >
// remember to remove the spaces .. if i put it normally it takes it as a html tag
#include < vector >
using namespace std;
class Base {
public:
virtual void pr() { cout << "Base" << endl;}
};
class Derv : public Base {
public:
void pr() { cout << "Derived" << endl; }
};
class Derv1 : public Derv {
public:
void pr() { cout << "Derived 1" << endl; }
};
int main()
{
vector< Base* > ptr;
ptr.push_back(new Base());
ptr.push_back(new Derv());
ptr.push_back(new Derv1());
for(vector< Base* >::iterator g = ptr.begin(); g != ptr.end(); ++g)
(*g)->pr();
cout << "\nNow going to Derv*\n\n";
vector< Derv* > ptr1;
ptr1.push_back(new Derv());
ptr1.push_back(new Derv1());
for(vector< Derv* >::iterator h = ptr1.begin(); h != ptr1.end(); ++h)
(*h)->pr();
//system("PAUSE"); //only windows
return 0;
}
hrishi, if what u r saying is true then the second vector's elements shouldn't show polymorphic behaviour but it does .. try it
dinesh.
#include < iostream >
// remember to remove the spaces .. if i put it normally it takes it as a html tag
#include < vector >
using namespace std;
class Base {
public:
virtual void pr() { cout << "Base" << endl;}
};
class Derv : public Base {
public:
void pr() { cout << "Derived" << endl; }
};
class Derv1 : public Derv {
public:
void pr() { cout << "Derived 1" << endl; }
};
int main()
{
vector< Base* > ptr;
ptr.push_back(new Base());
ptr.push_back(new Derv());
ptr.push_back(new Derv1());
for(vector< Base* >::iterator g = ptr.begin(); g != ptr.end(); ++g)
(*g)->pr();
cout << "\nNow going to Derv*\n\n";
vector< Derv* > ptr1;
ptr1.push_back(new Derv());
ptr1.push_back(new Derv1());
for(vector< Derv* >::iterator h = ptr1.begin(); h != ptr1.end(); ++h)
(*h)->pr();
//system("PAUSE"); //only windows
return 0;
}
hrishi, if what u r saying is true then the second vector's elements shouldn't show polymorphic behaviour but it does .. try it
dinesh.
Re: Polymorphism
Disclaimer :-) Whatever shit I have written in my 2 previous posts is entirely based on how "I" think the whole thing works.
If someone has any reliable information, please post.
If someone has any reliable information, please post.
Re: Polymorphism
And the penalty associated wouldn't be "much". An extra function call and extra space for a v-pointer for every object of the class having the virtual function. I do not think an extra function call would make that much of a difference as long as it's not executed large number of times, in a loop for example. The flexibility the whole thing offers is simply awesome.
Re: Polymorphism
I think Mohn's posting is correct. In your example Dinesh, only the base class has a virtual function and therefore pr only figures in the v-table of base. pr wouldn't figure in the v-table of derv (if it had one) at all since it's not virtual in derv. So a question of looking up derv's v-table doesn't arise. A call to a function using pointer of base class (even if it actually points to a derived class object) always goes to the base class. And only IF the function figures in the v-table, the corresponding function of the derived class is called.
Hope this helps.
Hope this helps.
Wednesday, November 26, 2003
Re: Polymorphism
" It will look to see if area() is a virtual function. If it is, it will look to see what slot the address of area() appears in Shape's vtable. Once it figures that out, it will go to Circle's vtable, find the same slot and dispatch the call to the address that is found there. "
are u sure about this? ... cause i always thought that the pointer created on the object directly points to the v-table of the class that is if i were to write
class Base {
public:
virtual void pr() { cout << "Base" << endl;}
};
class Derv : public Base {
public:
void pr() { cout << "Derived" << endl; }
};
and if i were to write in main()
Base* ptr;
ptr = new Derv();
ptr->pr();
the object created on the free store would have a pointer to Derv's v-table directly .. so why does it have to look at Base's v-table? for the index?
wouldn't it be a major run-time overhead if u had to go thru the base everytime u called a virtual function ... if any thing implementations say that the virtual function does not cause any major function mechanism overheads other than that pointer on the object and the v-table itself for each polymorphic class
just check it out ... i could not find enough info about the actual implementation of the v-table.
dinesh.
are u sure about this? ... cause i always thought that the pointer created on the object directly points to the v-table of the class that is if i were to write
class Base {
public:
virtual void pr() { cout << "Base" << endl;}
};
class Derv : public Base {
public:
void pr() { cout << "Derived" << endl; }
};
and if i were to write in main()
Base* ptr;
ptr = new Derv();
ptr->pr();
the object created on the free store would have a pointer to Derv's v-table directly .. so why does it have to look at Base's v-table? for the index?
wouldn't it be a major run-time overhead if u had to go thru the base everytime u called a virtual function ... if any thing implementations say that the virtual function does not cause any major function mechanism overheads other than that pointer on the object and the v-table itself for each polymorphic class
just check it out ... i could not find enough info about the actual implementation of the v-table.
dinesh.
Tuesday, November 25, 2003
Polymorphism
What is it? Why is it useful?
First consider a world WITHOUT polymorphism. This really just involves inheritance between classes. Here's a quick simple (classic) example.
// C++
class Shape
{
private:
int m_x;
int m_y;
public:
Shape( int x, int y ) : m_x( x ), m_y( y ) { }
void move( int x, int y )
{
this->m_x = x;
this->m_y = y;
}
double area() const
{
return 0;
}
};
class Circle : public Shape
{
private:
int m_r; // radius
public:
Circle( int x, int y, int r ) : Shape( x, y ), m_r( r ) { }
double area() const
{
return ( 3.14 * this->m_r * this->m_r );
}
};
class Rectangle : public Shape
{
private:
int m_w; // width
int m_h; // height
public:
Rectangle( int x, int y, int w, int h ) : Shape( x, y ), m_w( w ), m_h( h ) { }
double area() const
{
return ( this->m_w * this->m_h );
}
};
So, pretty basic inheritance going on here. Shape is the base class. It has a move() method which changes its x and y coordinates. Shape really doesn't have any concept of area so its area() method just reurns 0.
Circle and Rectangle both inherit from Shape. This means that they both get the m_x and m_y position variables as well as the move() method.
So you could do stuff like...
Shape s( 1, 2 );
s.move( 3, 4 ); // Calls Shape's move()
Circle c( 1, 2, 3 );
c.move( 3, 4 ); // Calls Shape's move()
Rectangle r( 1, 2, 3, 4 );
r.move( 3, 4 ); // Calls Shape's move()
Now since both Circle and Rectangle define area() in them, it overrides the area() they inherited from Shape. This is a good thing, since it gives each derived class the ability to provide custom functionality.
s.area() // always 0
c.area() // (3.14 * 3 * 3)
r.area() // (3 * 4)
So far so good.
The idea behind inheritance is that you could have a pointer to a base class and yet, have it point to derived objects. Consider this...
Shape* p;
p = new Shape( 1, 2 );
p->area();
Pretty straightforward - Calls Shape's area().
p = new Circle( 1, 2, 3 );
p->area();
What does this do? It still calls Shape's area(). Same thing here...
p = new Rectangle( 1, 2, 3, 4 );
p->area();
This is the big downside. It does NOT do the right thing. Why does this happen? Since p is a Shape pointer, it only has access to Shape's methods. How is it supposed to get to Circle's or Rectangle's area?
Enter virtual functions. This is the key to polymorphism.
If you make Shape's area() virtual, the correct area() will be called. The reason is that when you declare a function as virtual, the compiler will add a virtual table pointer to every object of the class hierarchy. This vtable contains the address of all virtual functions. Not only that, but they are kept in strict order. That means that the address Shape's area() will appear in the same slot in its vtable as the address of Circle's area() and Rectangle's area() appear in their vtables. So when you run this...
Shape* p;
p = new Circle( 1, 2, 3 );
p->area();
It will look to see if area() is a virtual function. If it is, it will look to see what slot the address of area() appears in Shape's vtable. Once it figures that out, it will go to Circle's vtable, find the same slot and dispatch the call to the address that is found there.
That's how you get dynamic behavior. Obviously, this comes at a price. All classes that have virtual functions will have vtable pointers. Plus, everything dynamic is done at runtime (obviously), so there's a performance penalty there too. You pay a price in space as well as time. But on the plus side, it allows you to grow your systems. You could come up with another class like Triangle, derive from Shape and define custom behavior for area() and it will do the right thing. This is especially useful if you have a collection of Shape objects. You could run through that collection and call virtual methods and it will do the right thing.
C++, Java and C# differ in the way you get polymorphic behavior. The behavior is the same, but how you enable it is different. I'll talk about that later.
First consider a world WITHOUT polymorphism. This really just involves inheritance between classes. Here's a quick simple (classic) example.
// C++
class Shape
{
private:
int m_x;
int m_y;
public:
Shape( int x, int y ) : m_x( x ), m_y( y ) { }
void move( int x, int y )
{
this->m_x = x;
this->m_y = y;
}
double area() const
{
return 0;
}
};
class Circle : public Shape
{
private:
int m_r; // radius
public:
Circle( int x, int y, int r ) : Shape( x, y ), m_r( r ) { }
double area() const
{
return ( 3.14 * this->m_r * this->m_r );
}
};
class Rectangle : public Shape
{
private:
int m_w; // width
int m_h; // height
public:
Rectangle( int x, int y, int w, int h ) : Shape( x, y ), m_w( w ), m_h( h ) { }
double area() const
{
return ( this->m_w * this->m_h );
}
};
So, pretty basic inheritance going on here. Shape is the base class. It has a move() method which changes its x and y coordinates. Shape really doesn't have any concept of area so its area() method just reurns 0.
Circle and Rectangle both inherit from Shape. This means that they both get the m_x and m_y position variables as well as the move() method.
So you could do stuff like...
Shape s( 1, 2 );
s.move( 3, 4 ); // Calls Shape's move()
Circle c( 1, 2, 3 );
c.move( 3, 4 ); // Calls Shape's move()
Rectangle r( 1, 2, 3, 4 );
r.move( 3, 4 ); // Calls Shape's move()
Now since both Circle and Rectangle define area() in them, it overrides the area() they inherited from Shape. This is a good thing, since it gives each derived class the ability to provide custom functionality.
s.area() // always 0
c.area() // (3.14 * 3 * 3)
r.area() // (3 * 4)
So far so good.
The idea behind inheritance is that you could have a pointer to a base class and yet, have it point to derived objects. Consider this...
Shape* p;
p = new Shape( 1, 2 );
p->area();
Pretty straightforward - Calls Shape's area().
p = new Circle( 1, 2, 3 );
p->area();
What does this do? It still calls Shape's area(). Same thing here...
p = new Rectangle( 1, 2, 3, 4 );
p->area();
This is the big downside. It does NOT do the right thing. Why does this happen? Since p is a Shape pointer, it only has access to Shape's methods. How is it supposed to get to Circle's or Rectangle's area?
Enter virtual functions. This is the key to polymorphism.
If you make Shape's area() virtual, the correct area() will be called. The reason is that when you declare a function as virtual, the compiler will add a virtual table pointer to every object of the class hierarchy. This vtable contains the address of all virtual functions. Not only that, but they are kept in strict order. That means that the address Shape's area() will appear in the same slot in its vtable as the address of Circle's area() and Rectangle's area() appear in their vtables. So when you run this...
Shape* p;
p = new Circle( 1, 2, 3 );
p->area();
It will look to see if area() is a virtual function. If it is, it will look to see what slot the address of area() appears in Shape's vtable. Once it figures that out, it will go to Circle's vtable, find the same slot and dispatch the call to the address that is found there.
That's how you get dynamic behavior. Obviously, this comes at a price. All classes that have virtual functions will have vtable pointers. Plus, everything dynamic is done at runtime (obviously), so there's a performance penalty there too. You pay a price in space as well as time. But on the plus side, it allows you to grow your systems. You could come up with another class like Triangle, derive from Shape and define custom behavior for area() and it will do the right thing. This is especially useful if you have a collection of Shape objects. You could run through that collection and call virtual methods and it will do the right thing.
C++, Java and C# differ in the way you get polymorphic behavior. The behavior is the same, but how you enable it is different. I'll talk about that later.
Saturday, November 22, 2003
Re: Macromedia Flex(ing)
In .NET, you have WinForms and WebForms. The development model for both is exactly the same. They both offer several different controls you can use and provide an event driven programming environment.
Right now, with WebForms you have complete separation of UI and code. UI is html and server controls, while code is in a "code behind" page which can be written in any language.
There is not as much clear separation with WinForms. The UI is also code. But if you follow good programming practice, the separation can be made easily. With Longhorn and XAML, they are moving towards total separation. UI = XAML, Code = Any language.
Yeah, Microsoft is discontinuing a standalone version of IE. I think this is pretty dumb. They should continue to offer a non-Longhorn IE as they continue to improve it. They are betting on rich client apps in a big way. With .NET they have come up with a way to deliver these apps like web apps. You download a basic skeleton of an application. As and when, you need certain functionality, it gets downloaded and run dynamically. They have made significant improvements in deployment. You can just copy an application from one folder to another (XCOPY) and it will just run. No messing with registry, no worrying about DLL hell etc... These improvements are great, but I still feel they need to release new IE versions for pre Longhorn Windows.
I agree that Flash is many times better/easier/convenient when developing rich internet apps. Probably the best thing is that it is truely cross platform. Your app will work and look the same in any browser. All the web standards - (X)HTML, CSS, DHTML, Javascript etc... - are implementation dependant. What works in one, will look awful on another. IE, since version 4 has done a supreme job of implementing these. Netscape 4 sucked big time. Mozilla (Netscape 6+) is more on par with IE. The differences are there but are minimal. So even though cross browser sites are quite annoying to develop, because of certain quirks of browsers, they are possible to do even with forks in the code.
Having said all that... I haven't seen many web apps use Flash at all. Yeah, they use it for animation, btu that's all. All "serious" web applications still make use of the web standards. It would actually feel quite wierd to use Flash apps. We are so used to seeing HTML forms and expecting certain behavior from them. I think, not a lot of people have taken Flash to be a serious development platform. It is still very much associated with the graphics/animation aspect. What do you think?
I have no idea about p2p. I have heard about the jxta sun project. I don't think Microsoft has made any noise regarding this. They mentioned something about having p2p capabilities in Longhorn, but that's it.
Right now, with WebForms you have complete separation of UI and code. UI is html and server controls, while code is in a "code behind" page which can be written in any language.
There is not as much clear separation with WinForms. The UI is also code. But if you follow good programming practice, the separation can be made easily. With Longhorn and XAML, they are moving towards total separation. UI = XAML, Code = Any language.
Yeah, Microsoft is discontinuing a standalone version of IE. I think this is pretty dumb. They should continue to offer a non-Longhorn IE as they continue to improve it. They are betting on rich client apps in a big way. With .NET they have come up with a way to deliver these apps like web apps. You download a basic skeleton of an application. As and when, you need certain functionality, it gets downloaded and run dynamically. They have made significant improvements in deployment. You can just copy an application from one folder to another (XCOPY) and it will just run. No messing with registry, no worrying about DLL hell etc... These improvements are great, but I still feel they need to release new IE versions for pre Longhorn Windows.
I agree that Flash is many times better/easier/convenient when developing rich internet apps. Probably the best thing is that it is truely cross platform. Your app will work and look the same in any browser. All the web standards - (X)HTML, CSS, DHTML, Javascript etc... - are implementation dependant. What works in one, will look awful on another. IE, since version 4 has done a supreme job of implementing these. Netscape 4 sucked big time. Mozilla (Netscape 6+) is more on par with IE. The differences are there but are minimal. So even though cross browser sites are quite annoying to develop, because of certain quirks of browsers, they are possible to do even with forks in the code.
Having said all that... I haven't seen many web apps use Flash at all. Yeah, they use it for animation, btu that's all. All "serious" web applications still make use of the web standards. It would actually feel quite wierd to use Flash apps. We are so used to seeing HTML forms and expecting certain behavior from them. I think, not a lot of people have taken Flash to be a serious development platform. It is still very much associated with the graphics/animation aspect. What do you think?
I have no idea about p2p. I have heard about the jxta sun project. I don't think Microsoft has made any noise regarding this. They mentioned something about having p2p capabilities in Longhorn, but that's it.
Friday, November 21, 2003
Macromedia Flex(ing)
macromedia has had a j2ee server jrun and some other java products. i was always expecting them to use flash as a frontend for j2ee apps (it was possible before but a little complicated). but this is purely revoltionary. flex sounds great but adoption by the community is important. it can be plugged into any application server. i hope to see the programming style soon.
fistly the j2ee api is in major flux. jsp the dynamic web pages in java do not have proper separation between code and ui. this led to a seperate ui package struts by jakarta,apache. currently jsf (java server faces) are being developed as an alternate ui which can be used in conjunction with jsp's for proper mvc architecture based apps. but jsf has not been released as a final version. i guess winforms performs a similar function ( is it for web ui also?) in .net. this is one reason why there are some major problems with the j2ee web tier right now. you can build great apps but it is messy. basically struts and jsf provide the prog. with java style programming and do add some javascript in the background. but the prog sees no intermingled code.
i am not sure about rich internet applications (ria). are ria for a better web experience only based on browsers? and i read that microsoft might even remove the browser in favour of other thick clients.( http://weblogs.java.net/pub/wlg/648 )
between html/css/java script and flash, flash would win because it can provide more "rich" controls. how much ever you tweak javascript etc i doubt how rich controls you can get. on the other hand flash was built for this. also how widespread is dhtml. i guess ms went out of its way with ie and dhtml, and not mozilla etc.
so as a prospective developer i have no idea where the future is. how rich controls does a client want is the question. does he want to get out of the browser to a thick client? suprisingly i think java is winning this race. you have flex, and sun packages a thick client with the default sdk download.( http://java.sun.com/products/javawebstart/ ) another interesting view is that the future is peer 2 peer. here jxta has some headway.( http://jxta.org ) please compare any similar .net projects.
a java desktop is going to be released sometime. basically suse linux with a lot of sun apps like staroffice and lots of java integration. and its not free!!
so i guess ms is in for a good fight... who'll win lets see..
for the moment lets hope that we get time to learn atleast one api...
fistly the j2ee api is in major flux. jsp the dynamic web pages in java do not have proper separation between code and ui. this led to a seperate ui package struts by jakarta,apache. currently jsf (java server faces) are being developed as an alternate ui which can be used in conjunction with jsp's for proper mvc architecture based apps. but jsf has not been released as a final version. i guess winforms performs a similar function ( is it for web ui also?) in .net. this is one reason why there are some major problems with the j2ee web tier right now. you can build great apps but it is messy. basically struts and jsf provide the prog. with java style programming and do add some javascript in the background. but the prog sees no intermingled code.
i am not sure about rich internet applications (ria). are ria for a better web experience only based on browsers? and i read that microsoft might even remove the browser in favour of other thick clients.( http://weblogs.java.net/pub/wlg/648 )
between html/css/java script and flash, flash would win because it can provide more "rich" controls. how much ever you tweak javascript etc i doubt how rich controls you can get. on the other hand flash was built for this. also how widespread is dhtml. i guess ms went out of its way with ie and dhtml, and not mozilla etc.
so as a prospective developer i have no idea where the future is. how rich controls does a client want is the question. does he want to get out of the browser to a thick client? suprisingly i think java is winning this race. you have flex, and sun packages a thick client with the default sdk download.( http://java.sun.com/products/javawebstart/ ) another interesting view is that the future is peer 2 peer. here jxta has some headway.( http://jxta.org ) please compare any similar .net projects.
a java desktop is going to be released sometime. basically suse linux with a lot of sun apps like staroffice and lots of java integration. and its not free!!
so i guess ms is in for a good fight... who'll win lets see..
for the moment lets hope that we get time to learn atleast one api...
Macromedia Flex
http://www.artima.com/weblogs/viewpost.jsp?thread=21896
Interesting what Macromedia is doing with their next version of Flash. Rahul, you'll probably be most interested in this.
Similar direction to what Microsoft is taking with Longhorn and XAML. Declarative UI seems to be the next BIG thing. Everyone is moving towards the "HTML way" of designing front ends.
How do you view Flash when designing web apps? I still don't see it as a serious contender. I still feel the HTML/CSS/DHTML/Javascript combination is going to win out for designing front ends hooking up to .NET/Java back ends. What dyou feel?
Interesting what Macromedia is doing with their next version of Flash. Rahul, you'll probably be most interested in this.
Similar direction to what Microsoft is taking with Longhorn and XAML. Declarative UI seems to be the next BIG thing. Everyone is moving towards the "HTML way" of designing front ends.
How do you view Flash when designing web apps? I still don't see it as a serious contender. I still feel the HTML/CSS/DHTML/Javascript combination is going to win out for designing front ends hooking up to .NET/Java back ends. What dyou feel?
Re: IP v5
Nice. It just occured to me that Netscape never released v5 of their browser either. This was after they open sourced it. They just jumped straight to 6 (officially). Well... atleast the mystry of ONE disappearing v5 is solved ;-)
We had a presentation given to us from a lady from IBM responsible for IPv6 in IBM's AIX OS. Here are her slides. It's good stuff... provides a nice overview. Fun fact she gave us - IP v6 has enough address capacity to represent a computer in every squarefoot of earth.
http://www.cs.utexas.edu/users/alex/ipv6.pdf
We had a presentation given to us from a lady from IBM responsible for IPv6 in IBM's AIX OS. Here are her slides. It's good stuff... provides a nice overview. Fun fact she gave us - IP v6 has enough address capacity to represent a computer in every squarefoot of earth.
http://www.cs.utexas.edu/users/alex/ipv6.pdf
Re: Basic overview of the Network stack
basic tcp/ip structure
© www.computer-solutions.co.uk
i'll just explain ARP (Address Resolution Protocol) ... once the packet of data with the ip header comes to the local network .. a machine (internal router) has a file with a table of ip's with thier corresponding machine address's ... thus this machine, looking at the ip decides which particular machine on the network the data is intended for ... if it were ethernet .. then the physical address would be the MAC(Media Access Control) of ur lan card ... if it doesn't find a corresponding MAC for the ip ... it broadcasts the message to the network and if there r any takers corresponding to that ip, it adds that machine's MAC to the table against that ip .. this on the whole is called Address Resolution Protocol
if i am wrong please correct ... been sometime since i looked at tcp/ip
by the way the subnet mask u put for ur machine is just the range of ip's forward and backward of ur ip, with whom u can exchange data ... without having to go through the router.
© www.computer-solutions.co.uk
i'll just explain ARP (Address Resolution Protocol) ... once the packet of data with the ip header comes to the local network .. a machine (internal router) has a file with a table of ip's with thier corresponding machine address's ... thus this machine, looking at the ip decides which particular machine on the network the data is intended for ... if it were ethernet .. then the physical address would be the MAC(Media Access Control) of ur lan card ... if it doesn't find a corresponding MAC for the ip ... it broadcasts the message to the network and if there r any takers corresponding to that ip, it adds that machine's MAC to the table against that ip .. this on the whole is called Address Resolution Protocol
if i am wrong please correct ... been sometime since i looked at tcp/ip
by the way the subnet mask u put for ur machine is just the range of ip's forward and backward of ur ip, with whom u can exchange data ... without having to go through the router.
IP v5
even when i was looking thru tcp/ip sometime back ... i was wondering where is ipv5 ... found this
What ever happened to IPv5?
Raffi Krikorian
Jun. 12, 2003 03:41 PM
Permalink
Because i work on small IP things, I'm constantly asked -- "Will they do IPv6?" "You know, 32-bits aren't enough for light switches... What about IPv6?" "You're not cool until you can do IPv6!" I know, I know. IPv6, whatever. Yes, of course they will do that.
But, what ever happened to IPv5?
IPng, Internet Protocol next generation, was conceived in 1994 with a goal for implementations to start flooding out by 1996 (yeah, like that ever happened). IPv6 was supposed to be the "god-send" over the well-used IPv4: it increased the number of bytes used in addressing from 4 bytes to 16 bytes, it introduced anycast routing, it removed the checksum from the IP layer, and lots of other improvements. One of the fields kept, of course, was the version field -- these 8 bits identify this IP header as being of version "4" when there is a 4 in there, and presumably they would use a "5" to identify this next gen version. Unfortunately, that "5" was already given to something else.
In the late 1970's, a protocol named ST -- The Internet Stream Protocol -- was created for the experimental transmission of voice, video, and distributed simulation. Two decades later, this protocol was revised to become ST2 and started to get implemented into commercial projects by groups like IBM, NeXT, Apple, and Sun. Wow did it differ a lot. ST and ST+ offered connections, instead of its connection-less IPv4 counterpart. It also guaranteed QoS. ST and ST+, were already given that magical "5".
And now as the Internet clock ticks, our PCs don't use IPv5. So we're moving onto 6.
Raffi Krikorian is a graduate student at MIT and the author of "TiVo Hacks".
What ever happened to IPv5?
Raffi Krikorian
Jun. 12, 2003 03:41 PM
Permalink
Because i work on small IP things, I'm constantly asked -- "Will they do IPv6?" "You know, 32-bits aren't enough for light switches... What about IPv6?" "You're not cool until you can do IPv6!" I know, I know. IPv6, whatever. Yes, of course they will do that.
But, what ever happened to IPv5?
IPng, Internet Protocol next generation, was conceived in 1994 with a goal for implementations to start flooding out by 1996 (yeah, like that ever happened). IPv6 was supposed to be the "god-send" over the well-used IPv4: it increased the number of bytes used in addressing from 4 bytes to 16 bytes, it introduced anycast routing, it removed the checksum from the IP layer, and lots of other improvements. One of the fields kept, of course, was the version field -- these 8 bits identify this IP header as being of version "4" when there is a 4 in there, and presumably they would use a "5" to identify this next gen version. Unfortunately, that "5" was already given to something else.
In the late 1970's, a protocol named ST -- The Internet Stream Protocol -- was created for the experimental transmission of voice, video, and distributed simulation. Two decades later, this protocol was revised to become ST2 and started to get implemented into commercial projects by groups like IBM, NeXT, Apple, and Sun. Wow did it differ a lot. ST and ST+ offered connections, instead of its connection-less IPv4 counterpart. It also guaranteed QoS. ST and ST+, were already given that magical "5".
And now as the Internet clock ticks, our PCs don't use IPv5. So we're moving onto 6.
Raffi Krikorian is a graduate student at MIT and the author of "TiVo Hacks".
RSS
Article introducing RSS as well as citing some good reader apps.
http://www.ciol.com/content/developer/2003/103111701.asp?nl=ctcd-11_21_2003
http://www.ciol.com/content/developer/2003/103111701.asp?nl=ctcd-11_21_2003
Basic overview of the Network stack
Decided to go with the Networking flow...
Networking is enabled through a series of protocols which are built on top of one another. There really are 4 main layers.
- application layer
- transport layer
- network layer
- sub-network layer
The application layer involves protocols like HTTP and FTP. All they generally do is send simple text messages to the transport layer.
The transport layer involves TCP and UDP. TCP provides a reliable connection-oriented service while UDP provides an unreliable connectionless service. When I say reliable, I mean that your message is guaranteed to be recieved by the destination. TCP accomplishes this by using a "hand-shake" before the sending of messages begins. Hand-shaking is just making sure a connection has been established. UDP on the other hand just sends the message and forgets about it. The message's receipt by the destination is not guaranteed. This layer deals with managing ports.
The network layer is IP. This protocol is also connectionless and unreliable. This level deals with the actual addresses of the computers. Most ubiquitous version of IP is v4 which is 4 bytes long. New version is v6 (no idea what the hell happened to v5). That is 16 freakn bytes.
Finally, the sub-network layer, as the name suggests, really is responsible for connecting various subnetworks together.
Generally, when a message is to be sent from one computer to another, the message travels down the network stack is the source computer and then up the stack in the destination computer.
Say we want to send message "m". Here's the basic process...
The application layer will add a protocol specific header to the message and send down to the transport layer.
( ahd, m )
The transport layer will take this message and add it's own protocol specific header to it.
( thd, ( ahd, m ) )
The header includes information regarding the source and destination port numbers and a checksum to detect corruption among other things. TCP also adds sequence numbers to the messages to detect for message loss and reorder. This is to enable message delivery guarantee.
The network layer will add the IP header to this message.
( nhd, ( thd, ( ahd, m ) ) )
The header includes the source and destination IP addresses, whether the message is fragmented and another checksum to detect corruption.
The sub-network layer will add another header (bet you never would've guessed that) and also a tail to the message.
( snhd ( nhd, ( thd, ( ahd, m ) ) ), sntl )
This will involve which sub-network to send this message to and another checksum.
As the message is received at the destination, each layer will remove their respective headers, parse it and send it to the appropriate protocol above.
One common element in almost all header's is a checksum. This is to enable each layer to check for corruption. Whatever layer the corruption is detected in will discard the message.
Networking is enabled through a series of protocols which are built on top of one another. There really are 4 main layers.
- application layer
- transport layer
- network layer
- sub-network layer
The application layer involves protocols like HTTP and FTP. All they generally do is send simple text messages to the transport layer.
The transport layer involves TCP and UDP. TCP provides a reliable connection-oriented service while UDP provides an unreliable connectionless service. When I say reliable, I mean that your message is guaranteed to be recieved by the destination. TCP accomplishes this by using a "hand-shake" before the sending of messages begins. Hand-shaking is just making sure a connection has been established. UDP on the other hand just sends the message and forgets about it. The message's receipt by the destination is not guaranteed. This layer deals with managing ports.
The network layer is IP. This protocol is also connectionless and unreliable. This level deals with the actual addresses of the computers. Most ubiquitous version of IP is v4 which is 4 bytes long. New version is v6 (no idea what the hell happened to v5). That is 16 freakn bytes.
Finally, the sub-network layer, as the name suggests, really is responsible for connecting various subnetworks together.
Generally, when a message is to be sent from one computer to another, the message travels down the network stack is the source computer and then up the stack in the destination computer.
Say we want to send message "m". Here's the basic process...
The application layer will add a protocol specific header to the message and send down to the transport layer.
( ahd, m )
The transport layer will take this message and add it's own protocol specific header to it.
( thd, ( ahd, m ) )
The header includes information regarding the source and destination port numbers and a checksum to detect corruption among other things. TCP also adds sequence numbers to the messages to detect for message loss and reorder. This is to enable message delivery guarantee.
The network layer will add the IP header to this message.
( nhd, ( thd, ( ahd, m ) ) )
The header includes the source and destination IP addresses, whether the message is fragmented and another checksum to detect corruption.
The sub-network layer will add another header (bet you never would've guessed that) and also a tail to the message.
( snhd ( nhd, ( thd, ( ahd, m ) ) ), sntl )
This will involve which sub-network to send this message to and another checksum.
As the message is received at the destination, each layer will remove their respective headers, parse it and send it to the appropriate protocol above.
One common element in almost all header's is a checksum. This is to enable each layer to check for corruption. Whatever layer the corruption is detected in will discard the message.
Re: simplest ever web server
ALL the networking "utilities" like Sockets etc.. are provided by Java in the java.net package. Similar functionality is provided in .NET in the System.Net namespace. This makes writing the web server fairly "easy"... easy is a very relative term obviously.
C++ does NOT provide this built-in functionality in their standard library. You have to explore some third party networking library to be able to code up something like this. So it is no where as easy to do.
You're right... HTTP is an application level protocol and so if FTP. I would assume that implementing FTP would be similar. You would need asymetric capabilties in FTP, whereas in HTTP its more unidirectional.
C++ does NOT provide this built-in functionality in their standard library. You have to explore some third party networking library to be able to code up something like this. So it is no where as easy to do.
You're right... HTTP is an application level protocol and so if FTP. I would assume that implementing FTP would be similar. You would need asymetric capabilties in FTP, whereas in HTTP its more unidirectional.
simplest ever web server (from Rahul)
adapted from http://www.oreillynet.com/pub/a/onjava/2003/04/23/java_webserver.html
a very simple web server has been implemented in this example using java. HttpServer is the main class in which a ServerSocket is created the constructor of which is
public ServerSocket(int port, int backLog, InetAddress bindingAddress);
here backlog is the maximum number of simultaneous clients. the port used is 8080 on localhost, 127.0.0.1 . the files in WEB_ROOT directory which points to user.dir can be served. this is the user directory, ~ in linux or My Documents in windows. i have so far tested the code only in linux and am not sure if the space in My Documents will cause problems.
the serverSocket is server socket as in it just opens a port and listens. when a connection is made to this port by a socket opened by a browser or any client it accepts, and the input stream is used to create a Request instance. the request object parses the request for http protocol messages like GET /index.html HTTP/1.1 . it simply seperates /index.html based on the indexof spaces. the request instance uri is used by the response instance. it simply opens the file and pases it to the outputstream. if the file does not exist it simply pases the http file not found message. voila!! as easy as that.
1.
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.File;
public class HttpServer {
//set the directory containig files here
public static final String WEB_ROOT =
System.getProperty("user.dir");
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir").toString());
HttpServer server = new HttpServer();
server.await();
}
public void await() {
ServerSocket serverSocket = null;
//set the port number
int port = 8080;
try {
serverSocket = new ServerSocket(port, 10, InetAddress.getByName("127.0.0.1"));
}
catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
//loop waiting for a request
while (true) {
Socket socket = null;
//create streams for input and output
InputStream input = null;
OutputStream output = null;
try {
socket = serverSocket.accept();
input = socket.getInputStream();
output = socket.getOutputStream();
//create Request object and parse
Request request = new Request(input);
request.parse();
//create Response object
Response response = new Response(output);
response.setRequest(request);
response.sendStaticResource();
//close the socket
socket.close();
}
catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
}
2.
import java.io.InputStream;
import java.io.IOException;
public class Request {
private InputStream input;
private String uri;
public Request(InputStream input) {
this.input = input;
}
public void parse() {
//read a set of characters from the socket
StringBuffer request = new StringBuffer(2048);
int i;
byte[] buffer = new byte[2048];
try {
i = input.read(buffer);
}
catch (IOException e) {
e.printStackTrace();
i = -1;
}
for (int j=0; j<i; j++) {
request.append((char) buffer[j]);
}
System.out.print("complete request: \n" + request.toString());
uri = parseUri(request.toString());
System.out.println("after parsing for file: \n" + uri);
}
//parse the http
private String parseUri(String requestString) {
int index1, index2;
index1 = requestString.indexOf(' ');
if (index1 != -1) {
index2 = requestString.indexOf(' ', index1 + 1);
if (index2 > index1)
return requestString.substring(index1 + 1, index2);
}
return null;
}
public String getUri() {
return uri;
}
}
3.
import java.io.OutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.File;
public class Response {
private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream output;
public Response(OutputStream output) {
this.output = output;
}
public void setRequest(Request request) {
this.request = request;
}
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
try {
//open file
File file = new File(HttpServer.WEB_ROOT, request.getUri());
System.out.println("request file path: \n" + HttpServer.WEB_ROOT+request.getUri() + "\n\n");
if (file.exists()) {
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while (ch!=-1) {
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, BUFFER_SIZE);
}
}
else {
//file not found
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 23\r\n" +
"\r\n" +
"File Not Found";
output.write(errorMessage.getBytes());
}
}
catch (Exception e) {
System.out.println(e.toString() );
}
finally {
if (fis!=null)
fis.close();
}
}
}
how would such code be written in c++?
also does anyone know some other protocol like ftp. correct me if i am wrong http is an application layer protocol. so if i can parse for ftp the above code should also work.
a very simple web server has been implemented in this example using java. HttpServer is the main class in which a ServerSocket is created the constructor of which is
public ServerSocket(int port, int backLog, InetAddress bindingAddress);
here backlog is the maximum number of simultaneous clients. the port used is 8080 on localhost, 127.0.0.1 . the files in WEB_ROOT directory which points to user.dir can be served. this is the user directory, ~ in linux or My Documents in windows. i have so far tested the code only in linux and am not sure if the space in My Documents will cause problems.
the serverSocket is server socket as in it just opens a port and listens. when a connection is made to this port by a socket opened by a browser or any client it accepts, and the input stream is used to create a Request instance. the request object parses the request for http protocol messages like GET /index.html HTTP/1.1 . it simply seperates /index.html based on the indexof spaces. the request instance uri is used by the response instance. it simply opens the file and pases it to the outputstream. if the file does not exist it simply pases the http file not found message. voila!! as easy as that.
1.
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.File;
public class HttpServer {
//set the directory containig files here
public static final String WEB_ROOT =
System.getProperty("user.dir");
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir").toString());
HttpServer server = new HttpServer();
server.await();
}
public void await() {
ServerSocket serverSocket = null;
//set the port number
int port = 8080;
try {
serverSocket = new ServerSocket(port, 10, InetAddress.getByName("127.0.0.1"));
}
catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
//loop waiting for a request
while (true) {
Socket socket = null;
//create streams for input and output
InputStream input = null;
OutputStream output = null;
try {
socket = serverSocket.accept();
input = socket.getInputStream();
output = socket.getOutputStream();
//create Request object and parse
Request request = new Request(input);
request.parse();
//create Response object
Response response = new Response(output);
response.setRequest(request);
response.sendStaticResource();
//close the socket
socket.close();
}
catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
}
2.
import java.io.InputStream;
import java.io.IOException;
public class Request {
private InputStream input;
private String uri;
public Request(InputStream input) {
this.input = input;
}
public void parse() {
//read a set of characters from the socket
StringBuffer request = new StringBuffer(2048);
int i;
byte[] buffer = new byte[2048];
try {
i = input.read(buffer);
}
catch (IOException e) {
e.printStackTrace();
i = -1;
}
for (int j=0; j<i; j++) {
request.append((char) buffer[j]);
}
System.out.print("complete request: \n" + request.toString());
uri = parseUri(request.toString());
System.out.println("after parsing for file: \n" + uri);
}
//parse the http
private String parseUri(String requestString) {
int index1, index2;
index1 = requestString.indexOf(' ');
if (index1 != -1) {
index2 = requestString.indexOf(' ', index1 + 1);
if (index2 > index1)
return requestString.substring(index1 + 1, index2);
}
return null;
}
public String getUri() {
return uri;
}
}
3.
import java.io.OutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.File;
public class Response {
private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream output;
public Response(OutputStream output) {
this.output = output;
}
public void setRequest(Request request) {
this.request = request;
}
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
try {
//open file
File file = new File(HttpServer.WEB_ROOT, request.getUri());
System.out.println("request file path: \n" + HttpServer.WEB_ROOT+request.getUri() + "\n\n");
if (file.exists()) {
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while (ch!=-1) {
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, BUFFER_SIZE);
}
}
else {
//file not found
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 23\r\n" +
"\r\n" +
"File Not Found";
output.write(errorMessage.getBytes());
}
}
catch (Exception e) {
System.out.println(e.toString() );
}
finally {
if (fis!=null)
fis.close();
}
}
}
how would such code be written in c++?
also does anyone know some other protocol like ftp. correct me if i am wrong http is an application layer protocol. so if i can parse for ftp the above code should also work.
Thursday, November 20, 2003
Final name
codeWord sounds good.
The W is in caps so that its like "a word about coding" + it has the alternate meaning as well.
The W is in caps so that its like "a word about coding" + it has the alternate meaning as well.
name final...
OK Dinesh... if you're cool with codeWord, let's go with it.
BTW, why is the W in caps?!
BTW, why is the W in caps?!
Wednesday, November 19, 2003
Vote Results - Tie between DevTalk and codeWord
Devtalk and codeWord have 7 points but codeWord got two 3 pointers ... should that be used as final arbitration or do u want to vote again or something ... man lets just decide .. this is taking too long :)
i didn't choose codeWord but i concede that i am fine with it :) ... so lets go with it!!
i didn't choose codeWord but i concede that i am fine with it :) ... so lets go with it!!
name
Hey guys,
My preferences -
codeword (3 pt)
codeX (2 pt)
progtalk (1 pt)
I want something related to coding and programming in the name! :-)
My preferences -
codeword (3 pt)
codeX (2 pt)
progtalk (1 pt)
I want something related to coding and programming in the name! :-)
Re: blog name vote
Agree...
+3 codeWord
+2 devtalk
+1 codeX
Yeah democracy is slow. Would you rather have a dictator (Dubya)?
+3 codeWord
+2 devtalk
+1 codeX
Yeah democracy is slow. Would you rather have a dictator (Dubya)?
blog name vote
i guess we'll arrive at a stalemate with each person voting for one or so.
rather i propose giving three names and point each name
1. devtalk (3 pts)
2. devbuzz (2pts)
3. codeWord (1 pt)
then we probably total and get a winner
man!! democracy is slow!!
rather i propose giving three names and point each name
1. devtalk (3 pts)
2. devbuzz (2pts)
3. codeWord (1 pt)
then we probably total and get a winner
man!! democracy is slow!!
Blog name
Ok. so here's the list of possibilities...
- devbuzz
- devtalk
- ideas inc.
- codeWord
- codeX
- progtalk
- penguin
This is purely democratic. Vote for one name. If there is a tie, we'll vote on that.
- devbuzz
- devtalk
- ideas inc.
- codeWord
- codeX
- progtalk
- penguin
This is purely democratic. Vote for one name. If there is a tie, we'll vote on that.
Re: hello world ... lol
Good to have you on Dinesh. We're all hoping for some serious c++ enlightenment from you.
Tuesday, November 18, 2003
hello world ... lol
hey ppl ... dinesh here .... well let me just introduce myself, if there were mother tongues for programmers mine would be C/C++ ... also done quite a bit in Prolog ... but that was some time ago .. basic interests r Graphics Programming (game engines) and Artificial Intelligence .. don't know much in the two but i'm learning.
mohnish & hrishikesh, i have heard quite a bit about u guys ... so it's good to finally talk to your'll.
by the way w.r.t the name of the blog i like
devbuzz
devtalk or
ideas inc.
adios,
dinesh.
mohnish & hrishikesh, i have heard quite a bit about u guys ... so it's good to finally talk to your'll.
by the way w.r.t the name of the blog i like
devbuzz
devtalk or
ideas inc.
adios,
dinesh.
Re: blog changes!!
Any of those names is fine by me...
devtalk
progtalk
devbuzz
My additions...
codeWord
codeX
How bout ++J# ?
Hrishi got any suggestions?
Rahul, why don't you invite Dinesh and after he joins then we can vote.
Made the font smaller.
devtalk
progtalk
devbuzz
My additions...
codeWord
codeX
How bout ++J# ?
Hrishi got any suggestions?
Rahul, why don't you invite Dinesh and after he joins then we can vote.
Made the font smaller.
Re: java swing hack for mdi interface windows menu
I really don't see why it is a dirtly solution. There is quite a clear separation between the two Main and IntFrame is there not? Why do you think it is bad?
Just one thing I noticed was that you don't need winNo. You have that info from windowList.size(). The range will be limited to whatever the dataype of windowList.size() is. But again is there really a problem if the max limit is long's MAX_VALUE? That is 2^63.
Can you give a simple example of Event Listeners?
Just one thing I noticed was that you don't need winNo. You have that info from windowList.size(). The range will be limited to whatever the dataype of windowList.size() is. But again is there really a problem if the max limit is long's MAX_VALUE? That is 2^63.
Can you give a simple example of Event Listeners?
this
Yeah I know you don't HAVE to use it. It's not a universal convention. I just adopted it so that it's explicit. This way there are NO possible conflicts with local variables having the same name as member variables - you know exactly which one you're talking about. I also recently started adding "m_" before member variables. I guess either one will work.
There are generally conventions used with various frameworks. The STL has a few. MFC/.NET/Java all follow conventions. This makes it easier to read the code and follow what's going on.
Anyway, there is another use for the "this" variable. You could have two functions with the same name in your class, one constant and one NON-constant. For example...
class Person
{
private:
int m_age;
public:
int& age()
{
return this->m_age;
}
const int& age() const
{
return this->m_age;
}
};
Both those mehtods do exactly the same thing, except the first one returns it by reference (you can change it), and the second returns by const reference (you CAN'T change it).
Now, this is just a simple returning of a member data value. What if it was a more complicated method? You'd have to write that algorithm twice. You can use "this" to simplify and resuse...
int& age()
{
return this->m_age;
}
const int& age() const
{
return ( *this ).age();
}
You can't just call age() from the second method because it will be an infinite recursive call. Using "this"... it will call the first age(), which will return a reference. It will then change it to a const reference and return that. In c++ going from non-const to const is implicit.
There are generally conventions used with various frameworks. The STL has a few. MFC/.NET/Java all follow conventions. This makes it easier to read the code and follow what's going on.
Anyway, there is another use for the "this" variable. You could have two functions with the same name in your class, one constant and one NON-constant. For example...
class Person
{
private:
int m_age;
public:
int& age()
{
return this->m_age;
}
const int& age() const
{
return this->m_age;
}
};
Both those mehtods do exactly the same thing, except the first one returns it by reference (you can change it), and the second returns by const reference (you CAN'T change it).
Now, this is just a simple returning of a member data value. What if it was a more complicated method? You'd have to write that algorithm twice. You can use "this" to simplify and resuse...
int& age()
{
return this->m_age;
}
const int& age() const
{
return ( *this ).age();
}
You can't just call age() from the second method because it will be an infinite recursive call. Using "this"... it will call the first age(), which will return a reference. It will then change it to a const reference and return that. In c++ going from non-const to const is implicit.
blog changes!!
new name for the blog..
how about devtalk //inspired by dev2dev by bea
or progtalk //inspired by p2p by wrox
also a friend of mine dinesh pillay suggested devbuzz.
so vote people.
i personally like devtalk.
and who is dinesh?? well he is a classmate of mine. does quite a lot of prog. especially in c++. he's not the java/.net dude. does major stuff in graphics engine dev. and other extra-terrestrial stuff. i guess i'll invite him over after we set a proper blog name and corresponding web address.
what say guys??
also do you feel that we can reduce the default size of the font by one??
work on what you feel is required mohn
more later
how about devtalk //inspired by dev2dev by bea
or progtalk //inspired by p2p by wrox
also a friend of mine dinesh pillay suggested devbuzz.
so vote people.
i personally like devtalk.
and who is dinesh?? well he is a classmate of mine. does quite a lot of prog. especially in c++. he's not the java/.net dude. does major stuff in graphics engine dev. and other extra-terrestrial stuff. i guess i'll invite him over after we set a proper blog name and corresponding web address.
what say guys??
also do you feel that we can reduce the default size of the font by one??
work on what you feel is required mohn
more later
java swing hack for mdi interface windows menu
in multiple document interface (mdi) apps one expected feature is the windows menu which shows all the open windows and the user can goto any window by clicking on the menu sub item. the windows menu is thus totally dynamic. i have implemented the same functionality in java swing (the java gui api). but as you will see it is pretty dirty.!! it does the work but you guys think of some other ways to implement the same. basically we all come from diff languages so thats a problem.
there are two classes, Main and IntFrame. Main is the actual class which forms the frame and IntFrame is the internal frame which gets formed everytime you make a new (file>new) internal window in the app window.
the code is...
1.
package blog;
public class Main extends javax.swing.JFrame {
private javax.swing.JMenu file;
private javax.swing.JMenuItem newItem;
private javax.swing.JMenuItem closeItem;
private javax.swing.JDesktopPane desktop;
private javax.swing.JMenu windows;
private javax.swing.JMenuBar jMenuBar;
private javax.swing.JMenuItem exitItem;
private long winNo;
private java.util.ArrayList windowList;
private java.util.ArrayList menuItemList;
public Main() {
//initialise the variables for the window menu
winNo = 0;
windowList = new java.util.ArrayList();
menuItemList = new java.util.ArrayList();
//build the remaining components in the app, basically the menu
initComponents();
}
private void initComponents() {
desktop = new javax.swing.JDesktopPane();
jMenuBar = new javax.swing.JMenuBar();
file = new javax.swing.JMenu();
newItem = new javax.swing.JMenuItem();
closeItem = new javax.swing.JMenuItem();
exitItem = new javax.swing.JMenuItem();
windows = new javax.swing.JMenu();
setTitle("Window menu");
setName("frame");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
getContentPane().add(desktop, java.awt.BorderLayout.CENTER);
file.setText("File");
newItem.setText("New");
newItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newItemActionPerformed(evt);
}
});
file.add(newItem);
closeItem.setText("CloseAll");
closeItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeItemActionPerformed(evt);
}
});
file.add(closeItem);
exitItem.setText("Exit");
exitItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitItemActionPerformed(evt);
}
});
file.add(exitItem);
jMenuBar.add(file);
windows.setText("Window");
jMenuBar.add(windows);
setJMenuBar(jMenuBar);
pack();
}
private void closeItemActionPerformed(java.awt.event.ActionEvent evt) {
dispAllWindows();
}
private void newItemActionPerformed(java.awt.event.ActionEvent evt) {
blog.IntFrame intFrame = new blog.IntFrame(getThis());
javax.swing.JDesktopPane dtp = this.getdesktop();
dtp.add(intFrame);
intFrame.show();
}
private void exitItemActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void exitForm(java.awt.event.WindowEvent evt) {
System.exit(0);
}
private Main getThis(){
return this;
}
public javax.swing.JDesktopPane getdesktop(){
return this.desktop;
}
// create a dynamic window menu item
public void regWindow(javax.swing.JInternalFrame frm){
winNo++;
java.lang.String cls = frm.getClass().toString();
int n = cls.lastIndexOf('.');
java.lang.String title = new java.lang.String(cls.substring(n+1)+" #"+winNo);
frm.setTitle(title);
windowList.add(frm);
javax.swing.JMenuItem winItem = new javax.swing.JMenuItem();
menuItemList.add(winItem);
winItem.setText(title);
winItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
winItemActionPerformed(evt);
}
});
windows.add(winItem);
}
// dispose a particular frame
public void dispWindow(javax.swing.JInternalFrame frm){
int position = windowList.indexOf(frm);
windowList.remove(position);
javax.swing.JMenuItem temp = (javax.swing.JMenuItem)menuItemList.remove(position);
windows.remove(temp);
windowList.add(position,"");
menuItemList.add(position,"");
}
// close all the open frames
private void dispAllWindows(){
int x = windows.getMenuComponentCount();
x--;
for(;x>=0;x--){
javax.swing.JMenuItem tempMenuItem = windows.getItem(x);
int position = menuItemList.indexOf(tempMenuItem);
javax.swing.JInternalFrame tempIntFrm = (javax.swing.JInternalFrame)windowList.remove(position);
tempIntFrm.setVisible(false);
tempIntFrm.dispose();
windows.remove(tempMenuItem);
menuItemList.remove(position);
}
int size = windowList.size();
while(size>0){
windowList.remove(size-1);
menuItemList.remove(size-1);
size--;
}
winNo=0;
}
private void winItemActionPerformed(java.awt.event.ActionEvent evt){
javax.swing.JMenuItem tempMenuItem = (javax.swing.JMenuItem)evt.getSource();
java.lang.String tempWin = tempMenuItem.getText();
int x = tempWin.lastIndexOf('#');
java.lang.String tempNo = tempWin.substring(x+1);
int n;
try{
n = java.lang.Integer.parseInt(tempNo);
javax.swing.JInternalFrame tempFrm = (javax.swing.JInternalFrame)windowList.get(n-1);
tempFrm.toFront();
}catch(java.lang.NumberFormatException nfe){
System.out.println("in client:+nfe");
}
return;
}
// main method
public static void main(String args[]) {
new Main().show();
}
}
2.
package blog;
/*this class defines the internal frame opened by Main*/
public class IntFrame extends javax.swing.JInternalFrame {
private javax.swing.JButton close;
private blog.Main parentFrame;
public IntFrame(blog.Main parent) {
this.parentFrame = parent;
//call to the Main parent class method in constructor
parentFrame.regWindow(this);
initComponents();
}
private void initComponents() {
close = new javax.swing.JButton();
setResizable(true);
setPreferredSize(new java.awt.Dimension(200, 100));
close.setText("close");
close.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeActionPerformed(evt);
}
});
getContentPane().add(close, java.awt.BorderLayout.CENTER);
pack();
}
private void closeActionPerformed(java.awt.event.ActionEvent evt) {
//call to the Main parent class method before dispose
parentFrame.dispWindow(this);
setVisible(false);
this.dispose();
}
}
to run first save both files into a directory called blog. goto cd ..
in a terminal
$> javac blog/IntFrame.java blog/Main.java
to execute
$> java blog.Main
the important methods in Main are regWindow, dispWindow and dispAllWindows. whenever a new internal frame is opened it calls regWindow which basically adds a menu item to the windows menu. the same during dispWindow on close of the internal frame. dispAllWindows closes all windows. read the three methods. using the class name of IntFrame, a title is given and so is a counter added. this is also used in the new menu item pointer. two arraylists windowList and menuItemList are the heart of the system. windowList contains references to the IntFrame instances and menuItemList the references for the dynamically added menuItems. during dispose i just remove the corresponding elements in both the arraylists. but to maintain the positioning of the other windows placeholder Object instances are added at the positions of the remove elements. the winno is also used for positioning and setting the title.
one problem is that the maximum no of openable internal frames is the range of long. also when you click on a windows menu item i have not changed focus to the window but just bring it to the front. (amazingly could not find the setFocus() method )
by now yu must have noticed what a dirty solution it is !! any ideas??
there are two classes, Main and IntFrame. Main is the actual class which forms the frame and IntFrame is the internal frame which gets formed everytime you make a new (file>new) internal window in the app window.
the code is...
1.
package blog;
public class Main extends javax.swing.JFrame {
private javax.swing.JMenu file;
private javax.swing.JMenuItem newItem;
private javax.swing.JMenuItem closeItem;
private javax.swing.JDesktopPane desktop;
private javax.swing.JMenu windows;
private javax.swing.JMenuBar jMenuBar;
private javax.swing.JMenuItem exitItem;
private long winNo;
private java.util.ArrayList windowList;
private java.util.ArrayList menuItemList;
public Main() {
//initialise the variables for the window menu
winNo = 0;
windowList = new java.util.ArrayList();
menuItemList = new java.util.ArrayList();
//build the remaining components in the app, basically the menu
initComponents();
}
private void initComponents() {
desktop = new javax.swing.JDesktopPane();
jMenuBar = new javax.swing.JMenuBar();
file = new javax.swing.JMenu();
newItem = new javax.swing.JMenuItem();
closeItem = new javax.swing.JMenuItem();
exitItem = new javax.swing.JMenuItem();
windows = new javax.swing.JMenu();
setTitle("Window menu");
setName("frame");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
getContentPane().add(desktop, java.awt.BorderLayout.CENTER);
file.setText("File");
newItem.setText("New");
newItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newItemActionPerformed(evt);
}
});
file.add(newItem);
closeItem.setText("CloseAll");
closeItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeItemActionPerformed(evt);
}
});
file.add(closeItem);
exitItem.setText("Exit");
exitItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitItemActionPerformed(evt);
}
});
file.add(exitItem);
jMenuBar.add(file);
windows.setText("Window");
jMenuBar.add(windows);
setJMenuBar(jMenuBar);
pack();
}
private void closeItemActionPerformed(java.awt.event.ActionEvent evt) {
dispAllWindows();
}
private void newItemActionPerformed(java.awt.event.ActionEvent evt) {
blog.IntFrame intFrame = new blog.IntFrame(getThis());
javax.swing.JDesktopPane dtp = this.getdesktop();
dtp.add(intFrame);
intFrame.show();
}
private void exitItemActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void exitForm(java.awt.event.WindowEvent evt) {
System.exit(0);
}
private Main getThis(){
return this;
}
public javax.swing.JDesktopPane getdesktop(){
return this.desktop;
}
// create a dynamic window menu item
public void regWindow(javax.swing.JInternalFrame frm){
winNo++;
java.lang.String cls = frm.getClass().toString();
int n = cls.lastIndexOf('.');
java.lang.String title = new java.lang.String(cls.substring(n+1)+" #"+winNo);
frm.setTitle(title);
windowList.add(frm);
javax.swing.JMenuItem winItem = new javax.swing.JMenuItem();
menuItemList.add(winItem);
winItem.setText(title);
winItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
winItemActionPerformed(evt);
}
});
windows.add(winItem);
}
// dispose a particular frame
public void dispWindow(javax.swing.JInternalFrame frm){
int position = windowList.indexOf(frm);
windowList.remove(position);
javax.swing.JMenuItem temp = (javax.swing.JMenuItem)menuItemList.remove(position);
windows.remove(temp);
windowList.add(position,"");
menuItemList.add(position,"");
}
// close all the open frames
private void dispAllWindows(){
int x = windows.getMenuComponentCount();
x--;
for(;x>=0;x--){
javax.swing.JMenuItem tempMenuItem = windows.getItem(x);
int position = menuItemList.indexOf(tempMenuItem);
javax.swing.JInternalFrame tempIntFrm = (javax.swing.JInternalFrame)windowList.remove(position);
tempIntFrm.setVisible(false);
tempIntFrm.dispose();
windows.remove(tempMenuItem);
menuItemList.remove(position);
}
int size = windowList.size();
while(size>0){
windowList.remove(size-1);
menuItemList.remove(size-1);
size--;
}
winNo=0;
}
private void winItemActionPerformed(java.awt.event.ActionEvent evt){
javax.swing.JMenuItem tempMenuItem = (javax.swing.JMenuItem)evt.getSource();
java.lang.String tempWin = tempMenuItem.getText();
int x = tempWin.lastIndexOf('#');
java.lang.String tempNo = tempWin.substring(x+1);
int n;
try{
n = java.lang.Integer.parseInt(tempNo);
javax.swing.JInternalFrame tempFrm = (javax.swing.JInternalFrame)windowList.get(n-1);
tempFrm.toFront();
}catch(java.lang.NumberFormatException nfe){
System.out.println("in client:+nfe");
}
return;
}
// main method
public static void main(String args[]) {
new Main().show();
}
}
2.
package blog;
/*this class defines the internal frame opened by Main*/
public class IntFrame extends javax.swing.JInternalFrame {
private javax.swing.JButton close;
private blog.Main parentFrame;
public IntFrame(blog.Main parent) {
this.parentFrame = parent;
//call to the Main parent class method in constructor
parentFrame.regWindow(this);
initComponents();
}
private void initComponents() {
close = new javax.swing.JButton();
setResizable(true);
setPreferredSize(new java.awt.Dimension(200, 100));
close.setText("close");
close.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeActionPerformed(evt);
}
});
getContentPane().add(close, java.awt.BorderLayout.CENTER);
pack();
}
private void closeActionPerformed(java.awt.event.ActionEvent evt) {
//call to the Main parent class method before dispose
parentFrame.dispWindow(this);
setVisible(false);
this.dispose();
}
}
to run first save both files into a directory called blog. goto cd ..
in a terminal
$> javac blog/IntFrame.java blog/Main.java
to execute
$> java blog.Main
the important methods in Main are regWindow, dispWindow and dispAllWindows. whenever a new internal frame is opened it calls regWindow which basically adds a menu item to the windows menu. the same during dispWindow on close of the internal frame. dispAllWindows closes all windows. read the three methods. using the class name of IntFrame, a title is given and so is a counter added. this is also used in the new menu item pointer. two arraylists windowList and menuItemList are the heart of the system. windowList contains references to the IntFrame instances and menuItemList the references for the dynamically added menuItems. during dispose i just remove the corresponding elements in both the arraylists. but to maintain the positioning of the other windows placeholder Object instances are added at the positions of the remove elements. the winno is also used for positioning and setting the title.
one problem is that the maximum no of openable internal frames is the range of long. also when you click on a windows menu item i have not changed focus to the window but just bring it to the front. (amazingly could not find the setFocus() method )
by now yu must have noticed what a dirty solution it is !! any ideas??
Re: hey guys!
Actually, you don't need to use this to refer to the data. Just the name of the variable would do; is it some convention that is universally followed or it's just that you've gotten used to it? Can't see any other 'practical' use (as in it's a must to use this) other than returning by reference.
BTW, you guys coded the Knight's Tour anytime? Basically, you need to return to the square on the chessboard (specified arbitrarily) that you started on; after covering every square ONLY once. And of course, you move like a knight does in a chess game. I haven't actually coded it but I thought about the algo in a lecture I was getting terribly bored in.
BTW, you guys coded the Knight's Tour anytime? Basically, you need to return to the square on the chessboard (specified arbitrarily) that you started on; after covering every square ONLY once. And of course, you move like a knight does in a chess game. I haven't actually coded it but I thought about the algo in a lecture I was getting terribly bored in.
Monday, November 17, 2003
re: hey guys!
Yeah neither of us have posted on blogs before either. So it's a first time for all of us.
I think there is a way to send an e-mail everytime someone posts, but what if we have several posts in one day? You'll get a whole bunch of emails. Quite annoying.
Regarding the "this" pointer. Yeah, I guess you're right. Actually, every instance method of a class has the "this" pointer as an argument. You just don't see it. It is passed in implicitly by the compiler. I think this is the way they connect methods to objects.
I use the "this" pointer in my code whenever I'm referring to data members of a class. I guess it's a coding standard I've adopted. Helps to differentiate between local and instance members.
I think there is a way to send an e-mail everytime someone posts, but what if we have several posts in one day? You'll get a whole bunch of emails. Quite annoying.
Regarding the "this" pointer. Yeah, I guess you're right. Actually, every instance method of a class has the "this" pointer as an argument. You just don't see it. It is passed in implicitly by the compiler. I think this is the way they connect methods to objects.
I use the "this" pointer in my code whenever I'm referring to data members of a class. I guess it's a coding standard I've adopted. Helps to differentiate between local and instance members.
hey guys!
Too bad I missed out on the discussion. Actually, I thought they send you a mail regarding updates on the postings on the blog. So I thought no mail, no postings (pretty lame, I know). This is the first time I'm posting on a blog. :-)
And don't worry about the lame shit. That's what blogs are for, right?!... education is just a side effect. :-)
I have zot fundaes on Java/.NET but I guess I'll pick up something by reading stuff you guys post. But tell you what, when I program in Java, I am gonna miss the *.
For a while, I was wondering about the use of the this pointer. I looked it up in a book and I guess the only practical use would be when you want to return the object by reference. What do you think?
And don't worry about the lame shit. That's what blogs are for, right?!... education is just a side effect. :-)
I have zot fundaes on Java/.NET but I guess I'll pick up something by reading stuff you guys post. But tell you what, when I program in Java, I am gonna miss the *.
For a while, I was wondering about the use of the this pointer. I looked it up in a book and I guess the only practical use would be when you want to return the object by reference. What do you think?
Correction Re: Allocation vs Initialization in Java/.NET
Actually I think I made a mistake regarding allocation in Java and reference types in .NET.
Our syntax in Java/.NET is wrong. You can't just say Foo f[ 10 ]. This is only legal in C++. This is how you do it in Java/.NET...
Foo[] f; // allocate on stack; f is a reference on the stack and is null (Java/.NET implicitly initialize to null)
f = new Foo[ 10 ]; // allocate on heap; f now points to an array on to heap, but all indices are null
for ( int i = 0; i < 10; ++i )
{
f[ i ] = new Foo( 1, 2 ); // initialize indices
}
Sorry about that. I'm in the c++ mindset.
Our syntax in Java/.NET is wrong. You can't just say Foo f[ 10 ]. This is only legal in C++. This is how you do it in Java/.NET...
Foo[] f; // allocate on stack; f is a reference on the stack and is null (Java/.NET implicitly initialize to null)
f = new Foo[ 10 ]; // allocate on heap; f now points to an array on to heap, but all indices are null
for ( int i = 0; i < 10; ++i )
{
f[ i ] = new Foo( 1, 2 ); // initialize indices
}
Sorry about that. I'm in the c++ mindset.
Sunday, November 16, 2003
Interesting research
aoccdrnig to a rscheearch at an Elingsh uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is taht frist and lsat ltteer is at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit porbelm. Tihs is bcuseae we do not raed ervey lteter by it slef but the wrod as a wlohe.
Pretty cool stuff.
Pretty cool stuff.
Powers of 10
Really really cool slide show... (Java applet) http://micro.magnet.fsu.edu/primer/java/scienceopticsu/powersof10/index.html
Re: Allocation vs Initialization in Java/.NET
Yeah I'm pretty sure in Java it will be what you posted. But there is a slight difference. Since in Java all user defined classes are reference types that will always be created on the heap, that array of Foo's will hold only references, not objects. So the size of the array will be sizeof( reference ) * 10. That reference size will be dependant on the OS. If it is 32 bit, it will be 32 bits, if 64 bit, 64 etc... (Is this right? Can you verify about reference/pointer size?)
In .NET you have the ability to create objects that will be created on the stack...
struct SFoo {} // created on Stack (this is NOT the same as C++ struct)
class CFoo {} // created on Heap
So I guess here you could have it both ways...
SFoo sf[ 10 ]; // allocate space for 10 SFoos on stack
for ( int i = 0; i < 10; ++i )
{
sf[ i ] = new SFoo( 1, 2 ); // initialize SFoo
}
CFoo cf[ 10 ]; // allocate space for 10 CFoo references on stack
for ( int i = 0; i < 10; ++i )
{
cf[ i ] = new CFoo( 1, 2 ); // allocate and initialize CFoo on heap and return reference to it
}
About C++ struct vs C# struct. The only difference between struct and class in C++ is that by default everything is public in struct and everything is private in class. You can create structs on the heap and classes on the stack and of course vice-versa. In C#, you can only create structs on the stack and classes on the heap.
And don't worry... I'm going to be posting some real lame shit too. Point is that we can share some stuff and learn off of each other.
BTW, when you're at ORielly, I'll be expecting some of them cool T-Shirts.
In .NET you have the ability to create objects that will be created on the stack...
struct SFoo {} // created on Stack (this is NOT the same as C++ struct)
class CFoo {} // created on Heap
So I guess here you could have it both ways...
SFoo sf[ 10 ]; // allocate space for 10 SFoos on stack
for ( int i = 0; i < 10; ++i )
{
sf[ i ] = new SFoo( 1, 2 ); // initialize SFoo
}
CFoo cf[ 10 ]; // allocate space for 10 CFoo references on stack
for ( int i = 0; i < 10; ++i )
{
cf[ i ] = new CFoo( 1, 2 ); // allocate and initialize CFoo on heap and return reference to it
}
About C++ struct vs C# struct. The only difference between struct and class in C++ is that by default everything is public in struct and everything is private in class. You can create structs on the heap and classes on the stack and of course vice-versa. In C#, you can only create structs on the stack and classes on the heap.
And don't worry... I'm going to be posting some real lame shit too. Point is that we can share some stuff and learn off of each other.
BTW, when you're at ORielly, I'll be expecting some of them cool T-Shirts.
Saturday, November 15, 2003
Allocation vs Initialization in Java/.NET
Hi all,
Great way for us to share some cool programming and other stuff. I was thinking about the role I could play in the blog especially with my vast tech knowledge. So i came to the conclusion that i will use humour to avoid you guys noticing how lame my blogs are. I promise to try to transform this blog to something like a cookery blog.
I am actually a very confused person on many issues relating to tech. and otherwise. like the future of java vs .net etc. so a lot of these things might come up. And otherwise I might just throw in a tech blog. So beware!!
Anyways this is a good start for me but i'll have to leave when they call me from oreilly.
Regarding to Mohnish's "allocation vs initialization in c++", could you continue your comparison wrt java or .net.
Would it be
Foo f[10]; //allocation
for (int i=0,i<10;i++){
f[i] = new Foo(1,2); //initialization
}
Keep blogging guys!!
Rahul
Great way for us to share some cool programming and other stuff. I was thinking about the role I could play in the blog especially with my vast tech knowledge. So i came to the conclusion that i will use humour to avoid you guys noticing how lame my blogs are. I promise to try to transform this blog to something like a cookery blog.
I am actually a very confused person on many issues relating to tech. and otherwise. like the future of java vs .net etc. so a lot of these things might come up. And otherwise I might just throw in a tech blog. So beware!!
Anyways this is a good start for me but i'll have to leave when they call me from oreilly.
Regarding to Mohnish's "allocation vs initialization in c++", could you continue your comparison wrt java or .net.
Would it be
Foo f[10]; //allocation
for (int i=0,i<10;i++){
f[i] = new Foo(1,2); //initialization
}
Keep blogging guys!!
Rahul
Friday, November 14, 2003
Allocation vs Initialization in C++
C++ gives you an amazing amount of control. One case of this is the allocation/initialization process. One of the advantages C++ has over C, is that it not only guarantees that a block of memory will be allocated, but also that the constructor will run automatically. A similar guarantee is made for deallocation and destruction as well.
When you say:
{
Foo f; // memory allocated & default constructor called
} // destructor called and memory deallocated
C++ allocates enough memory on the stack the size of Foo, and calls Foo's default constructor, giving those bits an identity (Foo). When it goes out of scope, it calls the destructor and deallocates that memory.
Same thing happens with creating objects dynamically on the heap...
Foo* p = new Foo; // memory allocated & default constructor called
Except now, you have to explicitly delete this object...
delete p; // destructor called & memory deallocated
The interesting thing is that there is a difference between keyword new and operator new. operator new is responsible for allocating the memory, while keyword new calls the constructor. So, you could call operator new directly and NOT have the constructor called.
Foo* p = static_cast( operator new( sizeof( Foo ) ) );
This will allocate memory on the heap for a Foo WITHOUT constructing it.
What's the point? Well, not much when you're dealing with individual objects, but they come in handy with arrays of objects.
Consider this line...
Foo* p = new Foo[ 10 ];
This will not only allocate memory for 10 Foos, but also call the default constructor for each of those Foo's. Allocation takes place in constant time O(1), initialization is linear O(N).
What if you wanted a different constructor to be called for each object? What if you didn't want the default? There is no way to specify which constructor you want called when dealing with arrays. You'd have an array of 10 default constructed Foos. You would then have to traverse it, delete those objects, create newly constructed individual objects and assign it to each index.
This is where operator new comes into play.
Foo* p = static_cast( operator new( 10 * sizeof( Foo ) );
for ( int i = 0; i < 10; ++i )
{
new ( &p[ i ] ) Foo( 1, 2 );
}
The first line allocates memory for 10 Foos. That's all it does. The loop goes through each index of the array and constructs a Foo with a 2 argument constructor.
The Standard Template Library actually has a class called allocator which encapsulates this functionality. Methods on that class are allocate(), construct(), destory() and deallocate().
So you can do something like...
Foo* p = allocator.allocate( 10 ); // allocate memory for 10 Foos
for ( int i = 0; i < 10; ++i )
{
allocator.construct( &p[ i ], Foo( 1, 2 ) ); // construct Foo with two argument constructor
}
for ( int i = 0; i < 10; ++i )
{
allocator.destroy( &p[ i ] ); // destroy Foo
}
allocator.deallocate( p ); // deallocate memory
There are a ton of minute details like this in C++. Because it gives you so much control it is such an interesting language.
When you say:
{
Foo f; // memory allocated & default constructor called
} // destructor called and memory deallocated
C++ allocates enough memory on the stack the size of Foo, and calls Foo's default constructor, giving those bits an identity (Foo). When it goes out of scope, it calls the destructor and deallocates that memory.
Same thing happens with creating objects dynamically on the heap...
Foo* p = new Foo; // memory allocated & default constructor called
Except now, you have to explicitly delete this object...
delete p; // destructor called & memory deallocated
The interesting thing is that there is a difference between keyword new and operator new. operator new is responsible for allocating the memory, while keyword new calls the constructor. So, you could call operator new directly and NOT have the constructor called.
Foo* p = static_cast
This will allocate memory on the heap for a Foo WITHOUT constructing it.
What's the point? Well, not much when you're dealing with individual objects, but they come in handy with arrays of objects.
Consider this line...
Foo* p = new Foo[ 10 ];
This will not only allocate memory for 10 Foos, but also call the default constructor for each of those Foo's. Allocation takes place in constant time O(1), initialization is linear O(N).
What if you wanted a different constructor to be called for each object? What if you didn't want the default? There is no way to specify which constructor you want called when dealing with arrays. You'd have an array of 10 default constructed Foos. You would then have to traverse it, delete those objects, create newly constructed individual objects and assign it to each index.
This is where operator new comes into play.
Foo* p = static_cast
for ( int i = 0; i < 10; ++i )
{
new ( &p[ i ] ) Foo( 1, 2 );
}
The first line allocates memory for 10 Foos. That's all it does. The loop goes through each index of the array and constructs a Foo with a 2 argument constructor.
The Standard Template Library actually has a class called allocator which encapsulates this functionality. Methods on that class are allocate(), construct(), destory() and deallocate().
So you can do something like...
Foo* p = allocator.allocate( 10 ); // allocate memory for 10 Foos
for ( int i = 0; i < 10; ++i )
{
allocator.construct( &p[ i ], Foo( 1, 2 ) ); // construct Foo with two argument constructor
}
for ( int i = 0; i < 10; ++i )
{
allocator.destroy( &p[ i ] ); // destroy Foo
}
allocator.deallocate( p ); // deallocate memory
There are a ton of minute details like this in C++. Because it gives you so much control it is such an interesting language.
Introducing Nude_Bastard
Hi guys,
I've started this blog for us to post our thoughts, comments, questions etc... about anything that's on our minds. Mostly I was thinking this blog would be more tech/programming related, but it doesn't have to be. If you come across a great article or something funny - just blog it.
This should start a small community of our own where we can share and relate our ideas to each other. I know we are not great authors or anything, but since this is sort of a "private" blog, we don't have to be. It's just between us. We can add people we know as we move forward.
This should be fun.
Mohnish
I've started this blog for us to post our thoughts, comments, questions etc... about anything that's on our minds. Mostly I was thinking this blog would be more tech/programming related, but it doesn't have to be. If you come across a great article or something funny - just blog it.
This should start a small community of our own where we can share and relate our ideas to each other. I know we are not great authors or anything, but since this is sort of a "private" blog, we don't have to be. It's just between us. We can add people we know as we move forward.
This should be fun.
Mohnish
Subscribe to:
Posts (Atom)