0

code:I want to access class members function display using generic ptr p...how should i do?

#include "stdafx.h"
#include<iostream>
using namespace std;
class car
{
public:  
int i,j;
  car():i(5),j(9){};
  car(int a,int b):i(a),j(b){}
  void display();
};
void car::display()
    {   cout<<i<<j;}
void main()
{
   car *obj=new car;
   void *p=obj;
***//how to access 'display() or i or j' using 'p'***
}
  • 3
    You can't unless you cast it. See this similar [question.][1] [1]: http://stackoverflow.com/questions/12995287/access-element-of-struct-passed-into-a-void-pointer – jazaman Jun 13 '14 at 04:21

3 Answers3

0

you need to declare how you want to treat the void pointer every time you use it. the way to do that is with casting (car*)p

car *obj=new car;
void* p;
p =obj;
((car*)p)->display();

system("pause");
Ori.B
  • 109
  • 6
  • 1
    Avoid C-style cast in C++! – Hiura Jun 13 '14 at 07:16
  • Please do not give c++ examples with c-style casts. They are a poor coding style choice (difficult to find in code, unsafe, non-extensible and they introduce code that fails silently when data types change). – utnapistim Jun 13 '14 at 07:29
0

It's strange , you know, when you declare a data of void* , then the data have no type infomation, that
means you dont know the content of data , it could be car, also it could be a trunk, float ,int... so why you should do this conversion?

wshcdr
  • 935
  • 2
  • 12
  • 27
0

Since you tagged C++ in your question I will answer this on C++

For these type of conversions use static casting: static_cast which can perform conversions between pointers to related classes, not only upcasts (from pointer-to-derived to pointer-to-base), but also downcasts (from pointer-to-base to pointer-to-derived). No checks are performed during runtime to guarantee that the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe

So back to your code:

#include<iostream>

using namespace std;

class car
{
public:
    int i, j;
    car() :i(5), j(9){};
    car(int a, int b) :i(a), j(b){}
    void display();
};
void car::display()
{
    cout << i << j;
}

void main()
{
    car *obj = new car;
    void *p = obj;
    //convert back to car from void. 
    car *casted_void_p = static_cast<car*>(p); //not safe - you may lose data or cause run time errors if casting from wrong object
    casted_void_p->display();
}
AK_
  • 1,879
  • 4
  • 21
  • 30