tinker thinker
(While I am here, might as well log it.)
Friday, July 15, 2011
Tuesday, June 7, 2011
An exception to C++ inheritance
Consider this code, with a Base class and on Derived class. foo() in Derived class calls foo(int).
1 class Base { 2 public: 3 void foo(int a) {} 4 } 5 6 class Derived : public Base { 7 public: 8 void foo() {foo(0);} 9 } |
Do you see any problem with the code above?
Neither did I!!!!! It is not that I am a master of C++. Just that I thought this was a basic inheritance stuff. The foo(int) in the derived class should resolve to the one in Base class. Surprisingly it doesn’t. This code when compiled gives an error of foo(int) not being defined. Though the exact error may differ from compiler to compiler.
Whereas, this code.
1 class Base { 2 public: 3 void foo(int a) {} 4 } 5 6 class Derived : public Base { 7 public: 8 void foo1() {foo(0);} 9 } |
OR
this, compiles fine.
1 class Base { 2 public: 3 void foo(int a) {} 4 } 5 6 class Derived : public Base { 7 public: 8 void foo() {Base::foo(0);} 9 } |
I was perplexed and exasperated to no end for not being able to figure out the reason. I felt that my basic C++ inheritance fundamentals are weak and that didn’t feel too good. And it came as a respite to know that this is an exception to the regular rule and was explained in the comments section here. I am pasting the comment here from AndreyT at stackoverflow.com for future reference. Though this explanation raised an interesting critique - was this done only to avoid the example given in the comment. As I couldn’t figure out any other scenario where there is an ambiguity for a type to be resolved.
“Judging by the wording of your question (you used the word "hide"), you already know what is going on here. The phenomenon is called "name hiding". For some reason, every time someone asks a question about why name hiding happens, people who respond either say that this called "name hiding" and explain how it works (which you probably already know), or explain how to override it (which you never asked about), but nobody seems to care to address the actual "why" question.
The decision, the rationale behind the name hiding, i.e. why it actually was designed into C++, is to avoid certain counterintuitive, unforeseen and potentially dangerous behavior that might take place if the inherited set of overloaded functions were allowed to mix with the current set of overloads in the given class. You probably know that in C++ overload resolution works by choosing the best function from the set of candidates. This is done by matching the types of arguments to the types of parameters. The matching rules could be complicated at times, and often lead to results that might be perceived as illogical by an unprepared user. Adding new functions to a set of previously existing ones might result in a rather drastic shift in overload resolution results.
For example, let's say the base class B
has a member function foo
that takes a parameter of typevoid *
, and all calls to foo(NULL)
are resolved to B::foo(void *)
. Let's say there's no name hiding and this B::foo(void *)
is visible in many different classes descending from B
. However, let's say in some [indirect, remote] descendant D
of class B
a function foo(int)
is defined. Now, without name hiding D
has both foo(void *)
and foo(int)
visible and participating in overload resolution. Which function will the calls to foo(NULL)
resolve to, if made through an object of type D
? They will resolve to D::foo(int)
, since int
is a better match for integral zero (i.e. NULL
) than any pointer type. So, throughout the hierarchy calls to foo(NULL)
resolve to one function, while in D
(and under) they suddenly resolve to another.
This behavior was deemed undesirable when the language was designed. As a better approach, it was decided to follow the "name hiding" specification, meaning that each class starts with a "clean sheet" with respect to each method name it declares. In order to override this behavior, an explicit action is required from the user: originally a redeclaration of inherited method(s) (currently deprecated), now an explicit use of using-declaration.
As you correctly observed in your original post (I'm referring to the "Not polymorphic" remark), this behavior migth be seen as a violaiton of IS-A relationsip between the classes. This is true, but apparently back then it was decided that in the end name hiding would prove to be a lesser evil.
“
Monday, June 6, 2011
Bootstrapping
This one took a really long time to come by, and maybe the idea in my head is faded. Or lets say I am not that enthusiastic to write about it anymore. I might be lazy as well.
Anyways, the general idea was this – ‘we use computers to make computers’.
This is a recurring theme all around us. Most import one is the life it self - the making of a conscious being from unconscious/inanimate things (as GEB book states it). And life is the ultimate goal of this bootstrapping process – that of a self-reflecting entity. Meaning we as humans can say I and address ourselves. On every step up in bootstrapping the entity goes to a higher level of abstraction and existence, challenging and defining new paradigms.
Go ahead and identify more such entities around you that follow this theme. You will be amazed at the variety of it.
Monday, August 9, 2010
Type-casting confusions
Type casting in C++ confuses me to no end, but what confuses me even more is the traditional typecasting expression. Consider this
member (cricket_team);
Now, when I see that line out of context, I can’t make out if that is a function call or type-casting. Which makes me wonder why would someone use that when it can me done like this
(member) cricket_team;
Friday, August 6, 2010
Upgrading MacBook Pro hard disk drive
I have a 13-inch MacBook Pro (7.1) with 250GB hard disk. And while installing Windows 7 to dual boot with OS X, I realized that I don’t have enough space for storage and installing applications. I had no choice but to upgrade. It is a good choice for two reasons, one I will be out of space before I realize and by then I would have invested considerable amount of time installing and customizing both OSes. Two, I can use the extracted disk for backup and Time Machine on OS X. With this in mind I order a 500GB (same brand and speed as already installed) hard disk drive (hdd) and a disk enclosure.
My order arrived on time, but little did I realize that I am missing two most important things to begin my work. Those were two types of screw drivers, Phillips #00 to open the back panel (pic. 4) and Torx 6 for removing the mounting screws (pic. 9) on the extracted disk to be put on the new disk (pic. 1 and 2). I read the MacBook Pro handout (pic. 3, the white booklet) on replacing hard disk, but it did not mention those screw drivers.
So, here is what I did to make the overall process of moving from old drive to a new one easy and safe. I started with noting down all the applications installed that are used frequently. Then exported all my calendar events, address book entries and bookmarks among other things to be imported on the new setup. Backed up important data, like pictures, videos and documents. Once this was done I was ready to put the new hdd. I followed the procedure for replacing hdd mentioned in the MacBook Pro booklet provided. The instructions in the booklet are clear, and the pictures below of my endeavor should make it even more lucid. Hence, I am skipping the details of installing it. Only word of caution is to be careful of static and not touching hdd on the top (to avoid harming head and disk) and bottom (to avoid touching the circuitry). Make sure that it is always handled on sides (as in pic. 9 and 10). General idea while handling electronic stuff is to read the cautionary instructions on the device.
Finally, I installed OS X. Though there was a hick up of installer not detecting hdd, besides everything else going fine. I resolved the hdd issue by running disk utility from utilities and creating one partition and formatting it. I also ran a sanity check on the hdd, to be sure. Furthermore, I also noticed that Windows 7 installation on MacBook Pro using bootcamp doesn’t finish in one go. It hung the first time and went fine the second time.
(I am sticking with Windows Live writer, as I couldn’t find a free and better alternative.)
Tuesday, August 3, 2010
Object Oriented Programming in C
If there is C++, what is the need of doing Object Oriented Programming (OOP) in C? Well I don’t have a compelling reason other than that it is a fun exercise. So, with that in mind, I am going to show an approach to OOP in C next. It is as close to OOP but not exactly OOP - for one it is not compiler restricted programming - that is compiler won’t crib if I break the OOP rules - and two, this implementation is short on some parameters of OOP. Which I will examine as I go along the example.
Note: The programmer should understand the underlying assumptions and should enforce the rules of programming to achieve OOP in C, as outlined below.
I will use two main features of C to attain encapsulation and function polymorphism. Namely, function pointers and static functions. Accompanied by segregation of public and private members in header files.
I start with a public header file –publicclass.h- of the class, which should be included wherever that class is needed.
typedef struct _testClass testClass; struct _testClass { int publicData; void (*publicFunc)(testClass*); }; // function to create testClass testClass *constructClass(void); void destructClass(testClass*); |
The structure testClass above defines public members of the class. Every function declared has to take a pointer to the structure of which it is a member. This is done to emulate 'this', as in C++. So, that we know the object being referred to. Also constructor and a destructor functions are defined, which create and destroy the class object respectively. These are like C++ constructors/destructors in a loose sense. These have to be called the first (for constructor) and the last (for destructor) in the object life cycle. The public function pointer defined will be discussed later.
Next I declare a private header file –privateclass.h- , to encapsulate the private data of the class. This is done by exclusively including this file in the class declaration file – class.c- and not anywhere else. This is one of the user coding restrictions to enforce data encapsulation.
#include "publicclass.h" typedef struct _itestClass itestClass; struct _itestClass { // public: testClass public; // private: int privateData; void (*privateFunc)(itestClass*); }; |
The structure above is called itestClass, where ‘i’ stands for internal or more appropriately private (I avoided using ‘p’ for private as to not confuse it with pointer). This structure looks similar to the previous one but with one difference, that is, it includes the public ‘testClass’ structure on the top - it is the first member. This serves a simple purpose of simplifying the pointer arithmetic, such that the pointer to ‘public’ (of ‘testClass’) will be the pointer to ‘itestClass’. This will become clear on the actual class implementation, below. Note, that the private functions takes pointer of ‘itestClass’.
Finally, the class implementation –class.c-. It is more or less self explanatory, where both public and private functions are defined. And in constructor assigned to the created object, and the pointer to the public structure –testClass- returned.
#include "publicclass.h" #include "privateclass.h" static void publicFunc(testClass *this) { itestClass *ithis = (itestClass*)this; printf("This is publicFunc\n"); this->publicData = 20; printf("From publicFunc: publicData: %d\n", this->publicData); ithis->privateData = 30; printf("From publicFunc: privateData: %d\n\n", ithis->privateData); ithis->privateFunc(ithis); } static void privateFunc(itestClass *ithis) { printf("This is privateFunc\n"); } testClass *constructClass(void) { itestClass *pobj = (itestClass*)calloc(1, sizeof(itestClass)); pobj->public.publicData = 0; pobj->public.publicFunc = publicFunc; pobj->privateData = 0; pobj->privateFunc = privateFunc; return &pobj->public; } void destructClass(testClass *pobj){ if (pobj) { free(pobj); } } |
As mentioned earlier ‘this’ (pointer to class object) is used to get ‘ithis’ (pointer to internal class object). In a class declaration all the functions are ‘static’ (except the constructor and destructor), to avoid namespace pollution and achieve function polymorphism. Such that, another class can be defined with a different implementation of the functions. Apart from function polymorphism class hierarchy can also be achieved and that is left as an exercise for the reader :-). Note: only this file includes the private header file –privateclass.h.
And lastly here is how to use the above built OOP structure in C.
#include "publicclass.h" int main (int argc, const char * argv[]) { testClass *pobj = constructClass(); pobj->publicData = 10; printf("From main: publicData: %d\n\n", pobj->publicData); // Error: not a member of obj(testClass) and itestClass is not visible // pobj->privateData = 20; pobj->publicFunc(pobj); destructClass(pobj); return 0; } |
Output.
From main: publicData: 10 This is publicFunc From publicFunc: publicData: 20 From publicFunc: privateData: 30 This is privateFunc |
Download this example from here.
(I am no longer using line numbers to post the code. I realized that with line numbers it is difficult to make changes in the post. On a change I have to update line numbers, else leave it discontinuous.)
Saturday, July 31, 2010
Publishing C/C++ code
It took me a while to figure out how to publish C/C++ code to the blog(spot). While doing so I messed up the post a few times. Finally, I got it working, and the way I wanted it, such that it looks same across the browsers and is well formatted. I tried a few things and some of them didn’t work. What didn’t work for me were plugins in Windows Live Writer (LW) to post code. Some of them didn’t show the colored text for the keywords and some didn’t have uniformity across browsers.
What worked was gvim/vim. Vim provides a command ‘TOhtml’ to generate html for the code with proper syntax – exactly the way seen in vim. But that is half the job, as BlogSpot doesn’t take the html code with <head> and <body> tags of the generated html. To get it right I had to do two things. First configure vimrc to generate the desired syntax and scheme (more on this later), and then copying the right part from the generated html. Here I will write about the way I did it using Live Writer (LW).
The published code in previous posts is inside a table, which is easy to draw in LW. So, first draw a table (1x1) in edit mode. Then in source mode copy the html generated by vim, starting from first <font> tag to the closing of it (which is at the end of the file) into that table. Even without LW this is easy to do, just add 1x1 table tags in BlogSpot edit post mode and then paste the generated html code. Explained below.
Copy the vim generated html code (as explained above) between these <td> tags.
<td valign="top" width="625"> {copy here} </td>
Note: Remove <pre> tags if any between the <td> tags. width can be adjusted to fit the blog.
After this add bgcolor of the <body> tag from the generated html to the <table> tag in the html code of the post. This will give the background color similar to vim scheme. At this point we have everything in place except the part, that this post won’t look same across the browsers. The reason being, first <font> tag in the pasted code. Where face is set as ‘monospace’ and not a particular fixed width font, like ‘Courier’. Hence, replace whatever there is with this ‘color="#ffffff" size="2" face="Consolas"’. This also gives the color to the ‘regular text’ in the code. In this case white (#ffffff).
This is how it will looked like on completion. Copied code marked in green.
<table border="0" cellspacing="0" cellpadding="3" width="625" bgcolor="#333333">
<tbody> <tr> <td valign="top" width="625">
<font color="#ffffff" size="2" face="Consolas, Courier New">
<Rest of the generated html code>
</font>
</td> </tr> </tbody>
</table>
1 int main(int argc, char * const argv[]) { 2 return 0; 3 } |
Here is the vimrc configuration used to get the syntax, scheme and the format. Just add these lines to the existing text. Line numbering can be turned off. If vimrc file can’t be located, typing in command - ‘e $MYVIMRC’ – will fetch it. html_use_css, is a switch to enable/disable CSS in the generated html code. The example above is without CSS styles.
set nu
colorscheme desert
syntax on
set guifont=Courier_New:h10
let html_use_css=0
(After writing this post, I am thinking of doing away with LW. I had hard time formatting and getting the post as I wanted.)