<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>hackinghat.com &#187; c++</title>
	<atom:link href="http://www.hackinghat.com/index.php/category/c/feed" rel="self" type="application/rss+xml" />
	<link>http://www.hackinghat.com</link>
	<description></description>
	<lastBuildDate>Wed, 19 May 2010 07:48:25 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Virtually pure, in a way only C++ can be</title>
		<link>http://www.hackinghat.com/index.php/c/virtually-pure-in-a-way-only-c-can-be</link>
		<comments>http://www.hackinghat.com/index.php/c/virtually-pure-in-a-way-only-c-can-be#comments</comments>
		<pubDate>Mon, 20 Jul 2009 12:13:48 +0000</pubDate>
		<dc:creator>Steve Knight</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[interviews]]></category>

		<guid isPermaLink="false">http://www.hackinghat.com/index.php/c/virtually-pure-in-a-way-only-c-can-be</guid>
		<description><![CDATA[What?
C++ was a boon for technical interviewers.   There was a time when C++ was about the only viable object-oriented programming language in a business environment.   In those days you pretty much had to know C/C++ to be an OO programmer.   So you could test someone&#8217;s depth of C++ knowledge [...]]]></description>
			<content:encoded><![CDATA[<h2>What?</h2>
<p>C++ was a boon for technical interviewers.   There was a time when C++ was about the only viable object-oriented programming language in a business environment.   In those days you pretty much had to know C/C++ to be an OO programmer.   So you could test someone&#8217;s depth of C++ knowledge (and thus their overall suitability) by just asking about all the messed up edge cases that make C++ really tricky to use.</p>
<p>Today we&#8217;ll be observing a hypothetical candidate Phil.   Phil has been a C++ programmer for 5 years (2 of which were at University) and has rated himself 9/10 on the C++ confidence scale that I asked him about at the beginning.   I&#8217;ve been talking to Phil about the various &#8216;overloaded&#8217; meanings of the keyword <strong>virtual</strong> in C++.  Phil has correctly answered what a virtual method was, but couldn&#8217;t get the one about the virtual base class.   </p>
<p>Even so, Phil is now into his stride and feeling pretty good about himself, so then I lay it on him:</p>
<blockquote><p>Phil, is it possible to ever call a pure virtual method?</p></blockquote>
<p>To which Phil  (and about 95% of other candidates) would heartily reply &#8220;No&#8221;.    And of course Phil would be wrong.  But that&#8217;s ok.   First I want Phil to tell me why a pure virtual method can not be called <strong>usually</strong>.   This  demonstrates a basic understanding, and then I would try and probe to see if Phil can guess the correct answer as to how a pure virtual method can be called and then the reason it&#8217;s possible.    </p>
<h2>So, what?</h2>
<p>If Phil didn&#8217;t get the answer straight away then Phil probably won&#8217;t get it at all.  This is not terribly surprising I suppose, and it&#8217;s not a reason to reject Phil.   The sad truth about being a C++ programmer is that you really need to know how C++ works, at some level, to be able to use it effectively.   I&#8217;m here to find out what Phil&#8217;s level really is.  The more oppurtunities I give him to tell me about those edge cases the better I can assess how good a (C++) programmer he is.</p>
<h2>How?</h2>
<p>So here is a code sample that under a couple of compilers (VC++ 2005 &#8211; Express, and GCC 3.4.4) produces the (un?)desired behaviour.   I wanted to try it under some more recent C++ compiler invocations but don&#8217;t have them available on the machine that I&#8217;m writing this.   Anyway, these two compilers seem fairly representative of what a lot of people are currently using.  </p>
<pre><code>
<font color="cyan">#include&lt;stdio.h&gt;</font>

<font color="yellow">class</font> A {
<font color="yellow">protected</font>:
	<font color="yellow">virtual void</font> Reset() = 0;
	<font color="yellow">void</font> Init()	{
		Reset();
	}
<font color="yellow">public</font>:
	A()	{
		Init();
	}
};

<font color="yellow">class</font> B : A {
<font color="yellow">protected</font>:
	<font color="yellow">void</font> Reset() 	{
		printf("Reset");
	}
<font color="yellow">public</font>:
	B() {
	}
};

<font color="yellow">int</font> main(<font color="yellow">int</font> argc, <font color="yellow">char</font>** argv)
{
	B b;
}</pre>
<p></code></p>
<p>And here is the result:</p>
<pre><code>$ g++ pvirt.cpp
$ ./a.out
pure virtual method called
      9 [sig] a.out 180 _cygtls::handle_exceptions: Error while dumping state (p
robably corrupted stack)
Segmentation fault (core dumped)</code></pre>
<p>So for those, like Phil, not fully aware of the vaguaries of calling pure virtual methods here is the explanation.  </p>
<blockquote><p>Pure virtual methods can be called from <strong>base-class constructors that attempt to indirectly call pure virtual methods.</strong></p></blockquote>
<p>The reason it's a problem is that C++ constructs objects inside-out, so base classes get built before derived classes.   If you then try and call a virtual method on a partially constructed object you will end up calling the base class copy of the virtual method.  This is because at the time you are in the base-class constructor the object is of type base-class and not of type derived-class.    Calling pure virtual methods from constructors sounds like a really bad idea then, and it is.   But there might be legitimate reasons to want to do it, which I'll come to in a minute.</p>
<p>Note that if you try and call the virtual method directly from the constructor, like so:</p>
<pre><code><font color="yellow">class</font> A
{
<font color="yellow">protected</font>:
	<font color="yellow">virtual void</font> Reset() = 0;
<font color="yellow">public</font>:
	A()	{
		Reset();
	}
};</code></pre>
<p>You will probably get a linker error because <strong>Reset()</strong> is pure and has no implementation, as you'd expect.  </p>
<h2>Why?</h2>
<p>So why might you want to do this at all then?   Well say you have a class hierarchy of objects that connect to a database for example.</p>
<p>So you dutifully create a <strong>Database</strong> base class with <strong>MySQLDatabase</strong> and <strong>OracleDatabase</strong> derived classes.    Now when you disconnect an already established connection you need to reset all the structures as if they had just been created.   The object is then ready to be reconnected.    So you create a virtual <strong>Reset()</strong> method in the base class that does this.   At the base level though this class should do nothing and you decide that your derived classes must define such a method so you very cleverly make it pure. You could then (but you probably wouldn't) write code like this:</p>
<pre><code>
<font color="yellow">void</font> Database::Disconnect() {
	Reset();
}</code></pre>
<p>And have the derived class handle the gorey details of the reset.   You want the same behaviour when you create a new object so you simply add the <strong>Reset()</strong> function to the <strong>Init()</strong> function that you created to deal with the fact that you had to write so many different types of copy constructor in C++!  Hey presto pure virtual method called.   </p>
<p>Note that if you had decided not to make the method pure and just put in an empty stub then this empty stub would be called instead (and not the derived version).   In some ways this is a harder error to track because there is no error just a silent refusal by the object system to call the derived version because it can't, because it doesn't exist yet.</p>
<p>The correct way to deal with this, unsurprisingly, is to not call <strong>Reset()</strong> from the base-class <strong>Init()</strong> function but from the derived constructor directly.</p>
<h2>Phil</h2>
<p>Thanks for coming Phil, we'll be in touch.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackinghat.com/index.php/c/virtually-pure-in-a-way-only-c-can-be/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Why not just use Haskell?</title>
		<link>http://www.hackinghat.com/index.php/c/66</link>
		<comments>http://www.hackinghat.com/index.php/c/66#comments</comments>
		<pubDate>Fri, 02 Nov 2007 10:36:58 +0000</pubDate>
		<dc:creator>Steve Knight</dc:creator>
				<category><![CDATA[c++]]></category>
		<category><![CDATA[rant]]></category>

		<guid isPermaLink="false">http://www.hackinghat.com/index.php/c/66</guid>
		<description><![CDATA[I am a fully paid up member of the ACCU.   I joined because it seemed most of my now ex-colleagues were members and I&#8217;m a sucker for peer pressure.
Anyway, as you&#8217;d expect from a magazine dedicated to C and C++ users it occasionally has articles about C and C++.   This quarter&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>I am a fully paid up member of the <a href="http://www.accu.org">ACCU</a>.   I joined because it seemed most of my now ex-colleagues were members and I&#8217;m a sucker for peer pressure.</p>
<p>Anyway, as you&#8217;d expect from a magazine dedicated to C and C++ users it occasionally has articles about C and C++.   This quarter&#8217;s <a href="http://accu.org/index.php/journals/1422">doozy</a> is from a chap we&#8217;ll call <a href="http://dphil.gxstudios.net/">Stuart</a>.   Now it looks like some of the things that Stuart is doing for his PhD are quite interesting.  However his article about the similarities he has managed to draw between <a href="http://www.haskell.org/haskellwiki/Haskell">Haskell</a> and using partial-template specializations in C++ gives me the shudders.    It is based, in part, on the work of <a href="http://www.amazon.com/Modern-C%2B%2B-Design-Programming-Patterns/dp/0201704315/ref=pd_bbs_sr_1/102-2220073-3920155?ie=UTF8&#038;s=books&#038;qid=1193998891&#038;sr=8-1">Andrei Alexandrescu</a>.   As charming as Mr Alexandrescu is in person I wouldn&#8217;t let him anywhere near any of my production C++ code (if I had any).  But that&#8217;s beside the point.</p>
<p>Now I have to admit that I don&#8217;t know any Haskell and I&#8217;m also not a lover of C++ much either so I can&#8217;t bring myself to actually RTFA.   However the article is full of little code snippets like this:</p>
<pre><code>
    template &lt;typename T&gt; struct Head;
    template &lt;int x, typename xs&gt;
       struct Head&lt;IntList&lt;x,xs&gt; &gt; {
       enum { value = x };
    };

    template &lt;typename T&gt; struct Tail;
    template &lt;int x, typename xs&gt;
       struct Tail&lt;IntList&lt;x,xs&gt; &gt; {
        typedef xs result;
    };
</code></pre>
<p>Why anyone would hate themselves enough to actually do this and write about it I don&#8217;t know.   Especially when you could just use Haskell and not have to wrap your head around this lunacy.</p>
<p>But I know there is a simple answer.  I should just unsubscribe from the magazine if I don&#8217;t like it.   But sadly for me it&#8217;s not that simple.   Stuart is obviously a clever guy, it almost goes without saying.   But he&#8217;s wasting his brain cycles.   Surely he must have better things to do with his time.   </p>
<p>Then I read <a href="http://www.doc.ic.ac.uk/~sue/475/AlanKay.html">this 2005 interview</a> with the glorious <a href="http://en.wikipedia.org/wiki/Alan_Kay">Alan Kay</a>.   If you have the time I suggest you read all of it because he makes some really very excellent points.   In reference to my pain though this one stands out:</p>
<blockquote><p>Perhaps it was commercialization in the 1980s that killed off the next expected new thing. Our plan and our hope was that the next generation of kids would come along and do something better than Smalltalk around 1984 or so. We all thought that the next level of programming language would be much more strategic and even policy-oriented and would have much more knowledge about what it was trying to do. But a variety of different things conspired together, and that next generation actually didnâ€™t show up. One could actually argueâ€”as I sometimes doâ€”that the success of commercial personal computing and operating systems has actually led to a considerable retrogression in many, many respects.</p>
<p>You could think of it as putting a low-pass filter on some of the good ideas from the â€™60s and â€™70s, as computing spread out much, much faster than educating unsophisticated people can happen.</p></blockquote>
<p>And while Stuart carries on trying to make C++ like Haskell, rather than just using Haskell, another wasted brain drops into the soup.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackinghat.com/index.php/c/66/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>My C++ wants to kill your momma</title>
		<link>http://www.hackinghat.com/index.php/c/my-c-wants-to-kill-your-momma</link>
		<comments>http://www.hackinghat.com/index.php/c/my-c-wants-to-kill-your-momma#comments</comments>
		<pubDate>Tue, 06 Feb 2007 08:48:12 +0000</pubDate>
		<dc:creator>Steve Knight</dc:creator>
				<category><![CDATA[c++]]></category>

		<guid isPermaLink="false">http://www.hackinghat.com/?p=16</guid>
		<description><![CDATA[&#8230; well actually it doesn&#8217;t.   But it sounded good when I made it up.   So recently I found myself needing to use a C++ partial function specialisation.   No-one was as surpsied as me when this happened.    
To say I was anti-templates would be too strong.  [...]]]></description>
			<content:encoded><![CDATA[<p>&#8230; well actually it doesn&#8217;t.   But it sounded good when I made it up.   So recently I found myself needing to use a C++ partial function specialisation.   No-one was as surpsied as me when this happened.    </p>
<p>To say I was anti-templates would be too strong.   I find the code they produce hard to follow, regardless of how elegant and efficient they really are.    But then they do serve a really useful need.    Obviously containers are an example of something where templates are indispensable.    So you can&#8217;t just write them off.</p>
<p>But now that we have the <a href="http://gcc.gnu.org/libstdc++/">standard library</a> (and <a href="http://www.boost.org">boost</a>) do mere mortals really need to worry or bother about templates in the large?   I think the answer to this is probably no.   </p>
<p>But then again it depends on what you&#8217;re doing.   And since I&#8217;ve started working on writing a wrapper around the <a href="http://rubyforge.org/projects/tibcorv/">TIBCo/RV library</a> for Ruby I found myself writing a lot of C++ code that was very similar apart from the types involved.   So then a little light bulb goes on in my head (40w supermarket own brand, cliche retardant) .   Surely I can write a template to do this for me?   This will mean that there&#8217;s only one code base for a bunch of similar behaviour and when I need to write that internationisation add-on (<a href="http://www.gnu.org/software/gettext/">i18n</a>) for my error messages I&#8217;ll only need to change one or two methods instead of a zillion.<br />
<span id="more-16"></span><br />
So I did the only honourable thing.   I broke out my trusty <a href="http://www.research.att.com/~bs/2nd.html">Stroustrup 2nd edition</a>.   Found the footnote about templates.   Grok&#8217;d the syntax again and I was away.   Shortly after I realised that in one of functions the integer processing needed bounds checking and the floats didn&#8217;t/couldn&#8217;t.   So I needed some different behaviour for float&#8217;s and int&#8217;s.   So, what I really needed now was some function templates that explicitly did something for floats and treated everything else the same.   Great, no problem.  Explicit instantiation is your friend.   Add a dash, mix well, retire.</p>
<p>The interesting part, at this point, was that I&#8217;d arrived in a new place.   A place where perhaps templates weren&#8217;t so bad after all.   So then I got to thinking what I really needed was code that could distinguish between signed and unsigned integers at compile time and surely there must be a way to do that.   And maybe if I partially specialise this function a bit and explicitly specialise that one a bit it will just magically work.</p>
<p>Since the project I was working on thus far had been written without the benefit of real objects I decided at the begining I only needed function templates to do the job.   Now to recap, I have just discovered that I needed partial specialisation of those templates to do different things for signed and unsigned ints.   Well like I say, no-one was as surprised as me to find myself here. </p>
<p>But as so often happens with C++ it&#8217;s always ready to kick you in the balls at any moment.   I couldn&#8217;t get the expected (guessed) partial function specialisation syntax to work.   So, a quick search of the web sought out this <a href="http://www.gotw.ca/publications/mill17.htm">jewel </a> that was predicatbly written by the man Sutter which explains the situation in depth.   Now I&#8217;m not going to rehash Sutter&#8217;s explanation.   He does it well, so there&#8217;s no need.   </p>
<p>But it&#8217;s like a drug, the next step would be to either use plain old functions (not possible in this case) or change my function templates into class templates to avoid the issue.   And before you know it you&#8217;ve just stepped a little further away from the target &#8230; sometimes this is a good thing and sometimes it&#8217;s a bad thing.   But with C++ you&#8217;ve got to watch it because before you know it you&#8217;ve templatized every living thing and no-one, not even <a href="http://www.research.att.com/~bs/">god</a> can tell you what you&#8217;ve done to yourself.</p>
<p>C++ is a weapon.   The US military probably wants to classify it as lethal.   But then they&#8217;d probably end up killing <a href="http://news.bbc.co.uk/go/rss/-/2/hi/uk_news/england/6333853.stm">Europeans </a>with it, dude.    </p>
<p>Sometimes you&#8217;ve got to sit back because the solution is far more complicated than the problem it solves.   And so I&#8217;m sitting back.   I&#8217;m good at that.   Very good indeed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackinghat.com/index.php/c/my-c-wants-to-kill-your-momma/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
