Monthly Archives: January 2015

Overloading functions

I was chatting with a friend of mine the other night, and I must confess, I was in a bit of bother about whether to blog this or not.  For a while now I’ve been aware that I take a lot of the language features of C++ for granted.  I know how to use an awful lot, but I don’t really get in to the guts of it. So while I know a lot of surface stuff, I don’t think the likes of Herb Sutter and Scott Meyers have anything to worry about just yet.

But as I was chatting with Craig, I was worried that what I was going to blog on would be career limiting, after all I’ve been coding in C++ for three years now, so surely I should know more right?  Well, as ever Craig had some very sage advice, so here goes.

I came across an interesting issue a few years back in a legacy system I was working on and at the time, I just ignored it as one of those things.  I’d been coding in C++ for a few months, and the developer in question told me, “don’t worry, I’ll fix it.”  And off he went, and I went on and did something else.

Now hands up who can tell me what mistake I made there?  That’s right, I should have asked the developer if I could pair program with him as he explained what the problem was and how to fix it if it ever happened again.

So the problem was there was a pair of overloaded functions, where one took a char* and the other took a string.  And this was causing some unexpected behaviour in the code.

So this struck me again as I was walking home from work one night, and I realised I never did find out what happens in that case.  So I decided to find out.  Albeit three years later.

So, let’s suppose we have the following code:

void printNum(int num) 
{
    cout << "Print num taking an int" << endl;
}

void printNum(double num)
{
    cout << "Print num taking a double" << endl;
}

 

And we call printNum and pass it a number like say 100.  How does the compiler know which version to call?  After all it could be either an int or a double.  Well, when I ran this code and passing it 100, it printed: “Print num taking an int.”  But why?

Well when faced with this, the compiler goes through an internal sequence to work out which one to call.

  1. It gets all the functions in the current scope that has the same name as the function we’re trying to call.  It ignores the ones that don’t have the same number of arguments.
  2. If there are no matches found, the compiler will return an error.
  3. If more than one is found, it selects the best match.
  4. If there’s no clear winner, then an ambiguous function call error is thrown by the compiler.

This looks quite simple, but how does the compiler then select the best match?  The compiler works on a ratings system for the way the types are passed in the call, and the competing lists match up in decreasing order of goodness.  The list is as follows.

  1. An exact match.
  2. A promotion, so for example if you have a function that takes an int, and you pass it a char, then the char is promoted to an int.
  3. A standard type conversion. So a conversion between a double and a float for example.
  4. A constructor or user defined conversions.

So in this instance, as we’ve passed the printNum an int, we’ll get the int version back, the same way if we passed it a double like say 46.5 we’ll get the double version back. 

But what if we have something like this?

void doSomething(char* something)
{
    cout << "Something with char*" << endl;
}

void doSomething(string something)
{
    cout << "Something with string" << endl;
}

And we call it thus: doSomething(“this is a test”);

Then what version does it call?  Well, for a start, the compiler gives me a warning when I compile this.  The warning is:

compilerError

So any bets on which one’s called when we run it?

runResult

It’s the char* one.  But why?  I’m not entirely sure yet, but from what I’ve read,  there is a default conversion rule to convert String literals to char *.  I am still looking in to this one, if I’m wrong then please please feel free to comment so I know.

So if we wanted the string version, then we’d need to cast our little test string to a string. 

Well hope all that helps, feel free to comment.

Happy coding.

Advertisements

An interview with Scott Meyers

Unless you’re very new to C++ programming, or have been living in a cave, then you will have heard of Scott Meyers. He is the author of the best selling book Effective C++, and his latest book Effective Modern C++ has just hit the bookshelves. Scott has been a C++ consultant and trainer for at least twenty-five years. And he trained me on the new stuff in C++ in September, and so I got to carry out this interview face to face.

How did you get in to computer programming? Was it a sudden interest? Or was it a slow process?

I started programming in grade school, and they had a time sharing system, and there was a math teacher who recruited me and a couple of other people. And she thought that we might enjoy programming, which started out by playing games. This was on a teletype system with a piece of paper in it, and it was a 110 baud teletype thing. You could play still some remarkably good games on that system.

After we played some games, we thought it would be fun to learn how to program. Which was probably the math teacher’s idea, to learn how to program. And we started to do that after school, as did my friend. And one thing led to another, and before you know it you’re spending way too much time in a former cloakroom closet with a teletype until they make you to go home at six o’clock at night.

It was probably a small room as well? Probably about the size of a large wardrobe?

It was a former “cloak” room. So it was like a walk in closet that had a teletype, which made a lot of noise. It was a mechanical device, so they stapled eggshells as noise dampeners all the way around. So it was this narrow room, with two young men, and a machine that made a lot of noise. It must have smelled horrendous!

What was the first program you ever wrote? And in what language was it written in? Also is it possible to provide a code sample of that language?

I don’t remember what the first program I ever wrote was. The earliest program off hand I can remember writing was a couple of years after that, but it was a horse racing program. Which had all the sophistication you would expect from somebody who was fourteen years old.

It basically involved as I recall, several horses, that had to go a certain distance and each iteration you chose a random number that would determine how much further they went; That’s about as sophisticated as it got. But it was kind of cool, because it’s on a teletype system. You can’t show things in real time, so what I’d do was have it type out x’s–like a histogram. But it’s a 110 baud teletype, so you’d see the all the x’s, and then you had to wait before it printed out the next set of results. So there was a certain degree of suspense in trying to figure out which horse was going to win. Nothing fancy, I’m sorry.

What about a modern language? Such as C or C++?

In C, because I learned from Kernighan and Richie, I wrote Hello World. In C++ I also wrote Hello World. Because there’s a lot of merit in making sure you have all the pieces together to write computer programs.

What would you say is the best piece of advice you’ve ever been given as a programmer?

I don’t know what the best piece of advice I’ve been given is, but I’m going to turn the question around a little bit. In my youth, there came a point where I thought I knew everything. And I was working as a software developer at the time. And I made a comment about blah blah blah being impossible because of blah! And another guy looked at me and went, “you know…” and laid it out for me, that it was not impossible, and how it was not impossible and it turned out I didn’t know everything. And that was an important learning experience for me, to recognise that there’s a lot of stuff I don’t understand.

And what I’ve since learned over the years is that there’s a reason for everything. And if you look at something and it makes no sense or it seems crazy or it seems stupid, there’s a reason for it. And whoever came up with whatever you’re looking at, or whatever group came up with what you’re looking at, they had a reason for doing it. And it was probably a reasonable reason.

I’ve found that to be extremely helpful over the years, just to say “why were these things done?” Someone had the goal of achieving something good. So if you’re looking at something that’s overly complicated or doesn’t look correct, then it’s important to find out why it’s done the way it is.

You are very well known for the Effective series, how did that come about? Did anything make you decide “there needs to be one of these”?

I was working as a trainer at the time, and I was training C programmers using five day hands on courses to learn C++. This was in the early 1990’s. So C++ was a simpler language back then, there were no exceptions, no templates, so it was as simpler thing. But when you teach C programmers, C++ programmers forget how much how much has to be learned. For the poor C programmers, they don’t know what a class is, they don’t know what a virtual function is, they don’t know what inheritance is, they don’t know what overloading is, they don’t know what constructors are, what destructors are, they don’t know what references are and how they’re different from pointers. The list goes on and on.

And so I would teach these poor C programmers over the course of five days how to use C++, and by Friday afternoon, their heads were swimming. They were thinking “I’m never going to be able remember all this.” And five days is not a lot of time. So on Friday afternoon, I’d write on the whiteboard, and tell them “It’s not that hard, let’s list the stuff you really need to remember.” So for example, if you have a base class, you need a virtual destructor, or if you have a class with pointers then you need a copy constructor and an assignment operator, or you should never redefine a default parameter value, these sorts of things.

And I found that this made them feel better. So that’s how the list of items began. I taught somewhere, and I don’t recall where, and the group said “you should write a book.” And I said I’m not going to write a book. Then another place said, “you should write a book,” and at that time I was working on my PhD, and I thought “well, I could work on my PhD, which is hard, or I could write a book, which can’t be as hard as working on a PhD.” So I decided to write the book instead. It was a spontaneous decision, and the book was well received, and everything was derived from that.

If you were to go back in time and meet yourself at 14 years old, when you were in the teletype room, what would you tell yourself?

You don’t know everything. The world is more complicated than you think it is. If I learned that lesson a lot sooner, that would have been useful

If you started your career as a programmer now, what would you focus on? Would it still be C++? And which field would you be interested in working in?

I think that for me personally, so much is a matter of happenstance. So the first language I learned was BASIC. I learned BASIC because the teacher said “Why don’t you learn BASIC?” And for that matter, the reason I learned C++, was because I in graduate school, I was required to TA [be a teaching assistant for] a course on software engineering, and the professor of that course decided “we’re going to use C++, so you must learn C++”. I didn’t choose either one of those things, they just sort of happened to me.

So I’m going to turn your question around a little bit, and say if it was my goal to introduce new people to programming, then what would I do? And what I would do is something mobile. I think that mobile devices are really interesting to people, and you can do all sorts of cool stuff. And I would do something using some technology which would allow people to get a lot done really quickly, with really fast turnaround. Because I think that’s what really hooks people: I can get this stuff to work. So the Hello World for me would probably be a way to very quickly write a little application that would send a message using some technology from one mobile phone to another using giant libraries that the programmers would have no idea about how they worked..

For a lot of new developers, it’s important that they see something happening, so when I started on Visual Basic for example, you’d draw a button, write some code behind it, click on it, and something would happen, so the fact they can see what they’ve written actually does something is quite important.

I think the immediate feedback combined with high likelihood for success is what draws people in. At some point you have to get in to the nitty gritty stuff. But I wouldn’t start with C++. For one thing it’s not fun, it has no graphics, it has no networking. A lot of stuff is missing.

What would you describe as the biggest “ah ha” moment or surprise you’ve come across when you’re chasing down a bug?

The one that comes to mind is when I found out that the cause of the problem I was running in to was an instruction in my program that was comparing two floating point numbers for equality. And it hadn’t occurred to me that because two things are mathematically equivalent, that does not mean you’ll get the same result on the computer. So I spent a lot of time tracking that down, and I’ve never forgotten that.

Have you got any tips for any new programmers that are chasing down bugs at the moment.

I would say that like most things, the way you get better at it is by doing more of it. But you have to do more of it, but learn at the same time. So seek out other people who are better at it than you are, and try to continue to get new sources of information. If you’re tracking down a bug, and it’s difficult, get someone to help you. Ask other people what their ideas are, and that will help you develop an intuition of what to look for.

Do you have any regrets as a programmer? For example wishing you’d followed a certain technology more closely or something like that?

You know, I really don’t. I’d like to know more about some areas, but at the same time, I’m happy where I am. As a specific example, in the mid 1990’s when Java became very popular, a lot of people in the C++ community went “this is a cool thing!” and they moved across to Java, and I decided not to move to Java. Primarily because I thought “I’ve already learned one programming language, and the last thing I need to do is to prove that I can learn another programming language.” Which allowed me to completely and utterly miss the boat on Java. But as a result, I’ve stayed constant to C++, and I’ve learned a lot from it, so I don’t really have regrets as far as that goes.

Do you code in other languages? Such as Python or other scripting languages?

C++ is my language. It’s the only thing I do. If I were an actual programmer, I’d have to do a lot more. There are some other languages I can do a little bit, but C++ is really what I do.

From what I’ve read of your website, a lot of your work today is training and consulting, so I was wondering how do you make your code samples relevant to what the programmer may face in their everyday work?

What I try to do is to have enough contact with real programmers on a regular enough basis that I get feedback from them as to whether what I’m advocating or what I’m saying makes sense. And because I’m not a practicing programmer right now, and because I work by myself and I’m not surrounded by a bunch of other people in a company, I try really hard to stay in touch with real programmers developing real code.

My experience is if you give people advice that’s not practical, they will tell you right away. If you give them advice that’s too simple, they’ll tell you right away. For example we just spent the last two days talking about this sort of stuff, and people ask questions, people make comments, they have funny looks on their faces. And you get feedback as to whether what you’re telling them seems relevant to their job. And that’s my primary goal.

I feel I should apologise, that I typed in some of your code during the course, and it didn’t do what you said it would do.

I love that! It reminds me I was in China at one time, and I was teaching a course and it happened to be on the internals of how certain things work. And I was talking about how virtual function tables are implemented under multiple inheritance.

So I do my presentation and I go “that’s how virtual functions are implemented under multiple inheritance.” And this one guy looks up from his computer and goes “no it’s not!”

So we looked at his compiler, and did some disassembly, and it turned out that the information I had was completely accurate for one compiler, and he was using a different compiler, which did things in a different way. So this is an example of how people keep me honest. So he learned that there were other ways to do it than that one compiler he was using, and I learned that there are other ways to do it other than the compiler I was using.

So I love it when people point out stuff that I wasn’t aware of.

Are you currently a mentor?  And if so, what do you do with your mentees?

No

Did you ever have a mentor yourself?

Certainly not by that name, I certainly learned from other people, but I never had a formal relationship with someone who was supposed to help me improve what I do. And in retrospect I learned mostly from peers with more or less the amount of experience as I did, but I wasn’t a practicing programmer for all that long. I was a programmer for three years.

As a trainer, I suppose you read quite a lot? What would you say is the best book you’ve read?

Nothing comes to mind. What I will say is that I don’t read many books. I read a giant amount of blog posts, I read Stack Overflow when I get a chance, or when I’m research, I read a lot of e-mail that I exchange with other people, I read a lot of papers, I read a lot of online shorter stuff. I don’t read a lot of books. For example, we talked earlier (in the course) about Anthony Williams’ book, C++ Concurrency in Action, I didn’t read that whole book. But for example, the chapter he has in there on the memory model is just killer! So I was very pleased with that. I don’t tend to sit down and read entire books, because in the C++ area, it’s uncommon to find a book that is filled with stuff I don’t already know.

So how do you go about learning new techniques then? For example, when the move paradigm came in C++ 11/14, how did you go about learning that? I suppose I’m really asking what’s your learning style? Do you read then dive in or do you dive in or is it a mix?

It depends on what I’m trying to learn. Let’s take something like C++ 11/14, something that’s technically defined by the standard. What I normally do in those conditions is start with blog entries, where people have written overview blog entries or something like that, so I can try to build a mental model. And if I have a questions, I get the questions answered in various ways, sometimes I turn to Stack Overflow, sometimes I turn to people that wrote standardisation proposals. I read a lot of standardisation proposals. I play around with compilers too, but I have to say that when it comes to standardisation-related stuff, compilers can be helpful, but if you want to know what the standard says, then you need to know what the standard says. So playing around with code is less useful, especially with technology that is newer, because compilers may not have implemented it yet.

On the other hand, for example we had that question in the course about what happens if you have an infinite loop in a constexpr function. To me, that’s a question compilers need to answer.

So we have an update to Effective C++, will you be doing an update to More Effective C++ and Effective STL? Or are all the updates incorporated in the new book?

To be clear, I didn’t update Effective C++. The new book is called Effective Modern C++. It has completely new information, so it’s not an update of Effective C++.

Sorry

No that’s fine; actually I’m eager to get the word out about that. It’s a completely new book. It would have been a lot less work had it been a new edition.

As to the question of whether I’ll be updating any of my other books, that remains to be seen. I will say that it’s unlikely that More Effective C++ will get updated. That book is now almost 20 years old. A lot of the information is still useful, but I’m not sure at this point it’s really worth updating.

Where do you think the next big shift in programming is going to come in? I’ve noticed you’ve done some stuff with D. Do you see that as the next big thing? And for the uninitiated, what is D?

I’m not doing anything with D, actually. There are people in the D community that would like me to do something with D, people who I respect. But that’s not my plan. I was asked to give a keynote talk at the most recent D conference, that’s what I did. I went and gave a talk to the D people, and I basically encouraged them to avoid creating a language as complicated as C++, that was basically my message for them.

As for the next big thing, I’m really bad at predicting that sort of thing, so I’m not going to even try.

Finally, what advice would you offer to kids or adults that are looking to start a career as a programmer?

The people who I know who are good at programming, who are happy with their lives–that kind of stuff, they do it because they love it. And so I would say that if you are looking at it as though to say “this would make a nice career” but your heart isn’t in it, maybe you should be looking elsewhere. On the other hand, if you play around with it, if it seems fun, if you like the idea of controlling machines or if you want to accomplish something, then you should just do it. Because it can be fantastically rewarding. It’s a “Follow your heart” kind of thing. Because if you don’t like it, it’s hard!

Thank you very much for your time.

You’re very welcome.