Search code examples
c++forward-declaration

using forward declarations instead of void* C++


Is it possible to use a forward declarations instead of void* or the preference is to use typedef ?

I am using a Specific class in my API. for the clients who use it, the class is represented by void* so the clients would not need to use the header files.

Which of these choices is better?

class A;
class b
{
    A* simple;
};

or

typedef void* A;
class b
{
    A simple;
};

Solution

  • You can definitely use something like:

    class A;
    
    class B {
        A* the_a;
    }
    

    instead of

    class B {
        void* the_a;
    }
    

    in your C++ code, and the former is better code than the latter. However, don't be quick to use raw pointers unless you really need to.

    Finally, I strongly recommend you avoid typedef'ing pointer types using names which do not clearly indicate the type is of a pointer, since that's confusing (and not useful).