I don't KISS, but I like to keep it DRY.

If you didn't get past the disgusting interpretation of that title, then you probably shouldn't be reading this blog ;)
I make elephants out flies and flies out of elephants, after-all, the human genetic code is 40% bananas!

Monday, February 8, 2010

Labeling revisited

While I, in one of my older blog-posts, brought up the idea of killing redundancy in code through extensive labeling, or tree-structuring, of the code itself, and not just of block statements, one of the ideas that followed, I was pleased to find redundant to some C++ syntax.

For the past week I've been looking into C++ through the eyes of Accelerated C++, and must say I am quite impressed, and find C++ very interesting, and my time to turn to it to be no less than perfect! I seem to have, at the very least, a basic idea of all the concepts that I have, so far, seen to make up C++, and so it is pretty easy to get going with it! However, back to the theme of the post, I've recently got past the part about the process of building classes and structs in C++, and found the following property rather pleasing:

In a struct the default protection level is public, until otherwise specified, while in a class the default protection level is private, but again, until otherwise specified. Now, that statement might not explain enough why I'm happy to know this, so let me show you an example:

class myclass {
  std::string name;
  //many many more private members
  public:
    double nice() const;
    //many many more public members

is equivalent to

struct mystruct {
  double nice() const;
  //many many more public members
  private:
    std::string name;
    //many many more private members

Of course, if the const memeber function uses name, or any other of the private members(which is most likely) then (I think) that will cause an outright compilation error, in which case we must rewrite it as follows:

struct mystruct {
  private:
    std::string name;
    //many many more private members
  public:
    double nice() const;
    //many many more public members

Again, this outlines how these protection labels work - there's a default one, which can be overridden by a number of subsequent such labels, each time canceling out the previous one. I guess this is also the reason structs are more usually used for open/simple data-structures, where private members are analytically trivial.

Basically, this is awesome syntax!

P.S. Sorry Python, I'm having an affair with C++.

No comments:

Post a Comment