Convert into void* - c++

how can I convert any object of my own class convert into pointer to void?
MyClass obj;
(void*)obj; // Fail

MyClass obj;
void *p;
p = (void*)&obj; // Explicit cast.
// or:
p = &obj; // Implicit cast, as every pointer is compatible with void *
But beware ! obj is allocated on the stack this way, as soon as you leave the function the pointer becomes invalid.
Edit: Updated to show that in this case an explicit cast is not necessary since every pointer is compatible with a void pointer.

You cant convert a non-pointer to void*. You need to convert the pointer to your object to void*
(void*)(&obj); //no need to cast explicitly.
that conversion is implicit
void* p = &obj; //OK

If you use the address, you can convert it to a void pointer.
MyClass obj;
void *ptr = (void*)&obj; // Success!

To do something which has any chance of being meaningful, first you have to take the address of an object, obtaining a pointer value; then cast the pointer.
MyClass obj;
MyClass * pObj = &obj;
void * pVoidObj = (void*)pObj;

i beleive you could only convert a pointer to an object to a pointer to void ???
Perhaps: (void*)(&obj)

In addition to the technical answers: Assert, that you avoid multiple inheritance or else you don't assign the address of super-class interfaces to a void*, for they will not be unique! E.g.
class S1 { int u; };
class S2 { int v; };
class MyClass : public S1, public S2 {};
MyClass obj;
S2* s2 = &obj;
void * p1 = &obj;
void * p2 = s2;
Here p1 and p2 (==s2) will be different, because the S2 instance in C has an address offset.

Related

Casting pointer to record type to non void pointer and back

Sometimes, e.g. when interfacing C++ and C code, it can make sense to cast a pointer to a C++ object to void * and back. The following should be well defined for any C++ class A:
// (1)
A *a = new A(...);
void *a_void = static_cast<void *>(a);
a = static_cast<A *>(a_void);
But what if instead of casting a to void * I cast it to some other type, in particular a declared but not defined record type?
// (2)
struct foo;
A *a = new A(...);
foo *a_foo = reinterpret_cast<foo *>(a);
a = reinterpret_cast<A *>(a_foo);
And if that is well-defined, what about doing it in a "roundabout" way like so:
// (3)
struct foo;
struct bar;
A *a = new A(...);
foo *a_foo = reinterpret_cast<foo *>(a);
bar *a_bar = reinterpret_cast<bar *>(a_foo);
a = reinterpret_cast<A *>(a_bar);
My intuition is that (1) and (2) are well-defined but (3) is not because technically it's missing a reinterpret_cast from a_bar * to a_foo *. Is that correct?

How to pass a nullptr?

Below is a simplified example of the code I'm working on. There's a function that takes class A pointer as an argument. I want to pass a pointer that has been initialized as nullptr. Without initializing it to some garbage temporary value first, is it possible to pass the nullptr?
class A
{
// stuff
};
class B
{
public:
A* pA1;
A objA;
std::vector<A*> vecB;
B() : pA1 (nullptr) { vecB.push_back(&objA); }
};
void function(A* p);
A* pA2;
int main()
{
B objB;
pA2 = objB.vecB[0];
function(objB.pA1);
return 0;
}
void function(A* p)
{
p = pA2;
}
In a comment, you said:
The point of the function is to make this happen: objB.pA1 = pA2
I think what you need to do is pass a reference to the pointer, instead of passing a pointer by value. Use:
void function(A*& p) // The argument type needs to be "A* &", not "A*"
{
// Now, the change will be visible in the calling program.
p = pA2;
}
Yes. Any raw pointer type can be assigned and therefore initialised with the nullptr value. Example:
static A* pA2 = nullptr;
aschepter has given me the answer in a comment, thank you very much.
void function(A* p)
should be
void function(A*& p)

Is the value discarded when converting to void pointer?

Code:
class CFoo
{
int a;
public:
CFoo():a(1){}
~CFoo(){}
getNum(){return a;}
};
void tfunc(void* data)
{
CFoo* foo = static_cast<CFoo*>(data);
std::cout << "Number: " << foo->getNum();
delete foo;
}
int main()
{
CFoo* foo = new CFoo;
void* dt = static_cast<void*>(foo);
tfunc(dt); // or tfunc(static_cast<void*>(food));
return 0;
}
When converting to a void pointer, isn't the value going to be discarded, if yes, how can foo->getNum() be valid?
When converting to a void pointer, isn't the value going to be discarded.
The value that is converted by your statement is the pointer, not the object to which the pointer points.
void* dt = static_cast<void*>(foo);
The value of the variable foo is the address of some CFoo object. The statement defines a new variable, dt, with the same value (i.e., foo and dt both point to the same address), but the compiler won't let you dereference *dt---it will not allow you to fetch a void object from that address---because the void type has no values.
When your program calls tfunc, the formal argument data also gets a copy of the same value (i.e., it points to the same address), and finally so does the local variable foo inside tfunc.
The declared type of the local foo inside tfunc is pointer to CFoo, so the compiler will allow you to dereference that; And, it makes sense because you know that foo actually does point to a legitimate CFoo object.

invalid conversion from ‘const type*’ to ‘type*’

I want to store through the constructor of a class a pointer to an object of another class. What is the correct way to do that?
If I substitute MyClass1* ptr with const MyClass1* ptr there is no error, but in this case I think that i cannot change ptr anymore. What is the correct way to achieve what i want?
example.cpp
class MyClass1{
public:
int a;
int b;
};
class MyClass2{
MyClass1* ptr;
public:
MyClass2(const MyClass1& obj){ptr = &obj;};
};
int main(int argc, char* argv[]){
MyClass1 object1;
object1.a = object1.b = 0;
MyClass2 object2(object1);
return 0;
}
Compile it through g++ -o example example.cpp give me this error
example.cpp: In constructor ‘MyClass2::MyClass2(const MyClass1&)’:
example.cpp:10:37: error: invalid conversion from ‘const MyClass1*’ to ‘MyClass1*’ [-fpermissive]
MyClass2(const MyClass1& obj){ptr = &obj;};
If you want to change the thing that ptr points to, then your function needs to take its argument by non-const reference (since MyClass2 might modify it):
MyClass2(MyClass1& obj) { ptr = &obj; }
Or, if you don't intend to modify the thing that ptr points to, then ptr should be declared as a pointer-to-const:
const MyClass1* ptr;
Both of these solutions will cause the code to compile.
Answering based on the last few comments.
I'll give you an example of const applied to pointers with ints,
int a = 2;
int b = 3;
int* p1 = &a; // Modifiable pointer modifiable value
const int* p2 = &a; // Modifiable pointer const value
int* const p3 = &a; // Const pointer modifiable value
const int * const p4 = &a; // Const pointer const value
*p1 = 3; // Ok, modifiable left-value
*p2 = 4; // Error: non-modifiable left-value
*p3 = 5; // Ok
*p4 = 6; // Error
p1 = &b; // Ok: modifiable pointer
p2 = &b; // Ok
p3 = &b; // Error
p4 = &b; // Error
In your case, you're looking for a modifiable pointer but a const value. So you want the second case,
const MyClass1* ptr;
(Which is what you originally had)
It would seem you didn't actually try to change the pointer?
I known from the comment that you want to modify the content of pointer, not the object pointer points to, so please declare the ptr pointer as const MyClass1* ptr. This means that ptr is a pointer which refers to a const MyClass1. So you can change the pointer, but you are not able to modify the object referenced by the pointer.
First remove the extra ;
MyClass2(const MyClass1& obj){ptr = &obj;}
can not pass const argument inside function( might modify it later), so this may work:
MyClass2(MyClass1 & obj){
ptr = &obj;
}
but here the value of &obj escapes the local scope.

what is Base*(*)()

Can someone please explain the Base*(*)() for me as in:
typedef std::map<std::string, Base*(*)()> map_type;
And how would one return it from a function?
I presume it is a function pointer, a Base* is returned, but what is this (*).
I found this in the following SO post Is there a way to instantiate objects from a string holding their class name?
Thanks
Base* (*)() is a type: pointer to function returning Base*. The * means that it is a pointer and the () are used to to override the precedence to ensure that the pointer applies to the function itself and not the return type.
You can return it from a function by returning the name of a function of the appropriate type.
E.g.
Base* f();
Base* (*g())()
{
return f;
}
It's the type of a function pointer of a function of signature Base*():
Base * foo();
Base * (*fp)() = &foo;
Or in your case:
map_type callbacks;
callbacks["Foo"] = &foo;
To invoke:
Base * p = callbacks["Foo"](); // same as "p = foo();"