# Saturday, November 05, 2005

C#, C++ and Rotor

As a C++ programmer, initially I was very disapponited when Microsoft took the .NET way. And I didn't really liked C#. Today, I have a different opinion (especially thanks to anonymous delegates, generics, all the other version 2 goodies and LINQ), but at the begininnig it was very hard for me to leave my loved COM+/C++ for .NET/C#.

I love a lot of C++ features, among them the possibility of separate declaration and definition, even phisically in two separate files (.h and .cpp). This is a need due to the early C++ compilers design, but it is also a way to guarantee a correct forma mentis (and to increase readability of the code).

Consider the following classes:

#pragma once

#include <iostream>

class Bar
{
public:

   void bar()
   {
      Foo* foo = new Foo();
      std::cout << "Bar" << std::endl;
   }
};

class Foo
{
public:
   void foo(Bar* owner)
   {
      bar->bar();
   }
};


There are two problems in this file: the obvious one, that it does't compile:

d:\VC\Test\Test.h(13) : error C2065: 'Foo' : undeclared identifier
d:\VC\Test\Test.h(13) : error C2065: 'foo' : undeclared identifier

the second one, that it does introduce a dependendency on iostream on anybody that is going to include it.
Now, if we separate definition

class Bar
{
public:
   void bar();
};

class Foo
{
public:
   void foo(Bar* owner);
};

and implementation

#include ".\test.h"
#include <iostream>

void Bar::bar()
{
   Foo* foo = new Foo();
   std::cout << "Bar" << std::endl;
}

void Foo::foo(Bar* bar)
{
   bar->bar();
}

the two problems are solved. Do you think my example is a stupid one? Sure, but think about the Model View Controller pattern, or about every system involving notifications, like a Window manager...

In C# there is no distinction: when you declare a type you must also give its implementation, the only exceptions being interfaces and abstract methods. So, how can a C# compiler deal with the above case? We will discover it in the next blog: time to do a little digging in Rotor!