Question

Partial class definition on C++?

Anyone knows if is possible to have partial class definition on C++ ?

Something like:

file1.h:

  
class Test {
    public:
        int test1();
};

file2.h:

class Test {
    public:
        int test2();
};

For me it seems quite useful for definining multi-platform classes that have common functions between them that are platform-independent because inheritance is a cost to pay that is non-useful for multi-platform classes.

I mean you will never have two multi-platform specialization instances at runtime, only at compile time. Inheritance could be useful to fulfill your public interface needs but after that it won't add anything useful at runtime, just costs.

Also you will have to use an ugly #ifdef to use the class because you can't make an instance from an abstract class:

class genericTest {
    public:
        int genericMethod();
};

Then let's say for win32:

class win32Test: public genericTest {
    public:
        int win32Method();
};

And maybe:

class macTest: public genericTest {
    public:
        int macMethod();
};

Let's think that both win32Method() and macMethod() calls genericMethod(), and you will have to use the class like this:

 #ifdef _WIN32
 genericTest *test = new win32Test();
 #elif MAC
 genericTest *test = new macTest();
 #endif

 test->genericMethod();

Now thinking a while the inheritance was only useful for giving them both a genericMethod() that is dependent on the platform-specific one, but you have the cost of calling two constructors because of that. Also you have ugly #ifdef scattered around the code.

That's why I was looking for partial classes. I could at compile-time define the specific platform dependent partial end, of course that on this silly example I still need an ugly #ifdef inside genericMethod() but there is another ways to avoid that.

 47  49263  47
1 Jan 1970

Solution

 44

This is not possible in C++, it will give you an error about redefining already-defined classes. If you'd like to share behavior, consider inheritance.

2008-09-26

Solution

 24

Try inheritance

Specifically

class AllPlatforms {
public:
    int common();
};

and then

class PlatformA : public AllPlatforms {
public:
    int specific();
};
2008-09-26