McLovin
McLovin

Reputation: 3417

Void pointer in C++

I learned that templates are the void* equivalents in C++. Is this true?

I have this issue in polling "events" off some procedure, when I have an EventType variable and I may also need to pass raw data that is related to that event.

struct WindowEvent {
    enum Type {WINDOW_SIZE_CHANGE, USER_CLICK, ...};

    void* data;
};

The user may then cast data to the necessary type, depending on the event type.

Is this approach okay in C++? Are there any better approaches?

Upvotes: 2

Views: 124

Answers (2)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145204

In C, which generally lacks support for polymorphism, void* pointers can be used to accept data of any type, along with some run-time representation of the actual type, or just knowledge that the data will be casted back to the correct type.

In C++ and other languages with support for polymorphism one will generally instead use either dynamic polymorphism (classes with virtual functions) or static polymorphism (function overloads and templates).

The main difference is that the C approach yields dynamic (run time) manual type checking, while the C++ approaches yield mostly static (compile time) and fully automated type checking. This means less time spent on testing and hunting down silly easily preventable bugs. The cost is more verbose code, and that means that there's a code size offset somewhere, under which the C approach probably rules for productivity, and above which the C++ approaches rule.

Upvotes: 4

Ed Heal
Ed Heal

Reputation: 59997

"I learned that templates are the void equivalents in C++. Is this true?"*

No - Templates maintain type safety

"Is this approach okay in C++?"

No

"Are there any better approaches?"

Depending on the use case one could use (for example)

class EventData {
   public:
      virtual int getData() = 0;
};

And then use the appropriate inherited class. Perhaps using smart pointers.

Upvotes: 0

Related Questions