-2

I am trying to access the object's value returned in the void pointer, how can i access those values x and y through void pointer variable.

How can I access the value returned in that void pointer ???

#include <iostream.h>
void* getDetector();

class DETECTOR
{
public:

    int x;
    int y;

    DETECTOR();
    ~DETECTOR();    
};

void* getDetector()
{
    return &DetectorObj;
}

DETECTOR::DETECTOR()
{
    x = 10;
    y = 20;
}

DETECTOR::~DETECTOR(){}

DETECTOR DetectorObj;

int main()
{
    void * getPtr = getDetector();

    cout<<getPtr->x;

    return 0;
}

2 Answers2

4

You can read the members of the object by returning the objects type and storing a pointer to that instead of a void*.

#include <iostream>
//DETECTOR definition..


DETECTOR DetectorObj;

DETECTOR* getDetector()
{
    return &DetectorObj;
}

int main()
{
    DETECTOR* getPtr = getDetector();

    cout<<getPtr->x;

    return 0;
}

There's no reason to return a void* here.


If you truly want to access them through void* then you can cast the result:

cout << static_cast<DETECTOR*>(getDetector())->x;

But this is considered bad bad practice. Please don't do this unless you're being held at gunpoint by your lecturer.


Also, it's <iostream>, not <iostream.h>, this is 2019.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
1

Assuming DetectorObj is of type DETECTOR and has an instance:

int main()
{
    DETECTOR* getPtr = (DETECTOR*)getDetector();

    cout<<getPtr->x;

    return 0;
}
EylM
  • 5,967
  • 2
  • 16
  • 28
  • 3
    yeah, but WHY on earth would the object be casted to void* to be returned ? Change the interface instead and return the actual type, or a base type, or something sane. – Jeffrey Jul 15 '19 at 13:51