using forward declarations instead of void* C++


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.


void*



Which of these choices is better?


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



or


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





Those are three completely different things...
– Rakete1111
Jul 1 at 7:41





Use them where? C++ is not a "one approach fits all" kind of language.
– StoryTeller
Jul 1 at 7:43






I honestly don't know how they are related to each other.
– iBug
Jul 1 at 7:44





@iBug: I think I know at least how two of these relate.
– einpoklum
Jul 1 at 7:47





@Rakete1111: See my answer.
– einpoklum
Jul 1 at 7:47




1 Answer
1



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 code like


typedef void* A_ptr;

class B {
A_ptr the_a;
}



since that is confusing and not useful.





i can write typedef void * A. is it wrong?
– nader
Jul 1 at 7:49





@nader: Yes, that's very wrong, since A is not a pointer. And this typedef will be extremely confusing. Also, while I figured out what you were asking, it wasn't very clear, which is why you got all the downvotes.
– einpoklum
Jul 1 at 7:52






but so many windows header files do something like this
– nader
Jul 1 at 7:57





@nader I wouldn't take any windows header files as the ultimate source of wisdom what to do best with advanced c++ (linux system headers neither BTW). These are mostly C-API definitions.
– πάντα ῥεῖ
Jul 1 at 8:03






@nader: That tells you something about the code quality of Windows then...
– einpoklum
Jul 1 at 8:07






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API