Friday, January 20, 2006

understanding C++

The problem with the C++ programming language is that it is a rather complicated language for the unexperienced programmer.

A colleague of mine decided that he wants to learn more C++ to really understand the software he is writing instead of writing code that the compiler just compiles by accident. He asked me to provide him with regular exercises to learn something about the language. Due to the fact that there might be some more people out there that want to learn additional stuff about the language I will do this within this Blog.

If you have an issue with the language you don't understand and you cannot find in the standard C++ books, feel free to suggest the issue for discussion here by sending me a mail. Given that the issue is really interesting, i.e. not a beginner's question, and I understand the issue myself I might add it here.

But now to the first exercise:

Consider the following application:

#include <iostream>

struct C {
    C& operator=(const C&) {
        std::cout << '=' << std::endl;
        return *this;
    }
};

int main() {
    C a;
    C b = a;   // (1)
    b = a;     // (2)
    return 0;
}

Explain why this application does print only one equal sign although the lines (1) and (2) are present.

2 comments:

Unknown said...

Couldn't find a contact link, so I hope you don't mind me commenting my guesses as comments, cuz these are really intriguing problems and I'm not sure I'm right :-)

I'd guess that the initialization in (1) gets converted to a call to the default copy constructor, and only the assignment in (2) uses the operator override?

Cheers & thanks for these interesting exercises from a former Student.

Robert said...

Well, there is my mail address in the profile. Thus you did the C++ issue exactly right but did not manage to get the mail address. ;-)