void* pointer to class
Sep 28, 2015 at 2:09am UTC
for example
1 2 3 4 5 6 7 8 9 10 11 12
class A
{
void function() {}
}
int main()
{
void * pA = &A;
pA->function();
return 0;
}
this doesn't work. error says : expression must have pointer-to-class type. The reason I use void* is that there are many possible type of data I want to get access via the pointer. So is there a solution? thanks!
Sep 28, 2015 at 2:16am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include <iostream>
struct A
{
virtual ~A() = default ;
virtual void function() const { std::cout << "A::function\n" ; }
};
struct B : A
{
virtual void function() const override { std::cout << "B::function\n" ; }
};
struct C : A
{
virtual void function() const override { std::cout << "C::function\n" ; }
};
int main ()
{
A a ;
B b ;
C c ;
A* pa = std::addressof(a) ;
pa->function() ;
pa = std::addressof(b) ;
pa->function() ;
pa = std::addressof(c) ;
pa->function() ;
}
https://en.wikipedia.org/wiki/Virtual_function
Sep 28, 2015 at 2:19am UTC
but what if I want this pointer to point to an integer, too?
Sep 28, 2015 at 2:47am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <iostream>
#include <boost/any.hpp> // <std/experimental/any>
template < typename SOME_TYPE > void foo( const SOME_TYPE& reference )
{
std::cout << "address: " << std::addressof(reference) << '\n' ;
// do something with the object
}
template < typename SOME_TYPE > void bar( const SOME_TYPE* pointer )
{
std::cout << "address: " << pointer << '\n' ;
if ( pointer != nullptr )
{
// do something with the object pointed to
}
}
struct A {};
struct B {};
int main()
{
const A a ;
const B b ;
const int i = 0 ;
foo(a) ; bar( std::addressof(a) ) ;
foo(b) ; bar( std::addressof(b) ) ;
foo(i) ; bar( std::addressof(i) ) ;
// http://www.boost.org/doc/libs/1_59_0/doc/html/any.html
boost::any pointer = std::addressof(a) ;
pointer = std::addressof(b) ;
pointer = std::addressof(i) ;
}
Topic archived. No new replies allowed.