dynamic_cast of void * - c++

I need to use dynamic cast void*
void *target = (MYClass*)target;//I am storing initially(to implment delegate mechanism)
....
delegateClass *delegate = dynamic_cast<delegateClass*>(target);
It is giving error cannot convert void*, I cannot use below code... since it is a delegate mechanism
delegateClass *delegate = dynamic_cast<delegateClass*>(((MYClass*))target);
How to get the type of target and implement... If i use typeid() i can get the name of the class but how to use typeid in the above equation instead of (((MYClass*))target).

You cannot use dynamic cast unless the original type of the variable had a vtable (ie, had virtual functions). This is because dynamic_cast requires run-time type information, which is recorded in the vtable; if the vtable is missing, the compiler doesn't know what type the object is.
You should declare a base class with a virtual destructor, and use pointers to this base class rather than void *.

If you must pass the object as a void * then you should use
delegateClass *delegate = static_cast<delegateClass*>(((MYClass*))target);
as there is no class relationship between the void *target and delegateClass. Here you are saying that you know that target _is_a_ delegateClass.
However this idiom is usually used for passing code through standard C interfaces and back.

I'm in a similar situation and being learning c++ style type casting. I referred to this llink http://www.cplusplus.com/doc/tutorial/typecasting/
From this what I can interpret is that the purpose of dynamic_cast is to ensure that the result of the type conversion is a valid complete object of the requested class. So when we try to convert from derived class to base class the conversion is smooth. But the vice versa is not true.
class CBase { };
class CDerived: public CBase { };
CBase b; CBase* pb;
CDerived d; CDerived* pd;
pb = dynamic_cast<CBase*>(&d); // ok: derived-to-base
pd = dynamic_cast<CDerived*>(&b); // wrong: base-to-derived
Now for that to work the base class should be polymorphic i.e. it should have a virtual function. When a class is polymorphic, dynamic_cast performs a special checking during runtime to ensure that the expression yields a valid complete object of the requested class. Have a look here.
class CBase { virtual void dummy() {} };
class CDerived: public CBase { int a; };
int main () {
try {
CBase * pba = new CDerived;
CBase * pbb = new CBase;
CDerived * pd;
pd = dynamic_cast<CDerived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast" << endl;
pd = dynamic_cast<CDerived*>(pbb);
if (pd==0) cout << "Null pointer on second type-cast" << endl;
} catch (exception& e) {cout << "Exception: " << e.what();}
return 0;
}
Here the code tries to perform two dynamic casts from pointer objects of type CBase* (pba and pbb) to a pointer object of type CDerived*, but only the first one is successful. Even though both are pointers of type CBase*, pba points to an object of type CDerived, while pbb points to an object of type CBase. Thus, when their respective type-castings are performed using dynamic_cast, pba is pointing to a full object of class CDerived, whereas pbb is pointing to an object of class CBase, which is an incomplete object of class CDerived so it returns a null pointer to indicate the failure.
So I'd suggest you to make use of the static_cast which offers bi directional type casting i.e. from derived to base class and also from derived to base class. But in that case programmer needs to ensure that the conversion is safe becasue the type checking is not performed at run time as in case of dynamic_cast.
In your code here either make target to point to deligate class object before conversion(but make sure Myclass is polymorphic) otherwise you can go for static_cast.
This explaination is based on my very recent reading on the topic and I'd suggest you to refer to Effective C++ for more insight about this. I hope this will help. :)

Related

Definition of "static type" and "dynamic type" [duplicate]

I want to know what are static and dynamic type checking and the differences between them.
Static type checking means that type checking occurs at compile time. No type information is used at runtime in that case.
Dynamic type checking occurs when type information is used at runtime. C++ uses a mechanism called RTTI (runtime type information) to implement this. The most common example where RTTI is used is the dynamic_cast operator which allows downcasting of polymorphic types:
// assuming that Circle derives from Shape...
Shape *shape = new Circle(50);
Circle *circle = dynamic_cast<Circle*> shape;
Furthermore, you can use the typeid operator to find out about the runtime type of objects. For example, you can use it to check whether the shape in the example is a circle or a rectangle. Here is some further information.
C++ has very little support for dynamic type checking. One way is through dynamic_cast and other is through type id. Both can be used only when RTTI support is enabled in compiler.
TYPE& dynamic_cast<TYPE&> (object);
TYPE* dynamic_cast<TYPE*> (object);
The dynamic_cast keyword casts a datum from one pointer or reference type to another, performing a runtime check to ensure the validity of the cast.
If you attempt to cast to pointer to a type that is not a type of actual object, the result of the cast will be NULL. If you attempt to cast to reference to a type that is not a type of actual object, the cast will throw a bad_cast exception.
Make sure there is at least one virtual function in Base class to make dynamic cast work.
// expre_typeid_Operator.cpp
// compile with: /GR /EHsc
#include <iostream>
#include <typeinfo.h>
class Base {
public:
virtual void vvfunc() {}
};
class Derived : public Base {};
using namespace std;
int main() {
Derived* pd = new Derived;
Base* pb = pd;
cout << typeid( pb ).name() << endl; //prints "class Base *"
cout << typeid( *pb ).name() << endl; //prints "class Derived"
cout << typeid( pd ).name() << endl; //prints "class Derived *"
cout << typeid( *pd ).name() << endl; //prints "class Derived"
delete pd;
}
Assume you have:
class A {};
class B:A {};
A* a = new B();
B* b = new B();
For the static type, you look at how the variable is declared.
A* a = ...
B* b = ...
So the static type of a is A* (or to put it another way, the static type of *a is A).
And the static type of b is B* (or to put it another way, the static type of *b is B).
Note that a and b have a static type that is fixed by it's declaration - it doesn't matter what you put in them, they will keep the same static type. ("static" means "unchanging").
For the dynamic type, you look at what happens to be in the variable right now.
a = new B();
b = new B();
So the dynamic types of a and b are both B* (or to put it another way, the dynamic types of *a and *b are both B).
Note that the dynamic type can change - if you did a = new A() then they dynamic type of a just changed to A*. Sometimes you don't know what the dynamic type is - e.g. if you do a = somefunc() then a might have dynamic type A*, B* or even C* (if some code you haven't seen defines C as a subclass of A or B).
If A had a virtual method on it, then you could use dynamic_cast to figure out what the dynamic type is. (Typically, if you're using this sort of code, you want to be able to do delete a; for that to work A's destructor has to be virtual. And making A's destructor virtual is enough for dynamic_cast to work).
There are multiple types of casts available in C++.
The most common would be to use static_cast in order to cast a variable from one type of pointer to another. However, you can also use dynamic_cast, which will check to make sure (at runtime) that the pointers are of the correct type. With dynamic_cast, if the pointer is not of the right type, at runtime, it will return 0 instead.
// Assume these classes exist
// class A
// class B
// class C : B
C* c = new C();
A* a = new A();
B* b = static_cast<B*>(a); // this will work!
b = dynamic_cast<B*>(a); // b == NULL
b = dynamic_cast<B*>(c); // b is valid
Static type checking is type checking that is done at compile time. This is the only type of type checking that C++ does. Dynamic type checking is type checking done at run time. This is usually seen in dynamic interpreted languages, but is less common in compiled languages. Last I checked, C++ doesn't do any sort of dynamic type checking.
Edit: Apparently I'm out of date. See Reed's comment below.

C++ Inheritance. Changing Object data Types

I am having trouble with forcing data type changes has on my own objects. I have a base class say A and two classes derived from A called B and C. I pass objects B and C to a function that checks which type of object it is (B or C). Here is some example code below and the question to my problem:
enum ClassType {"B", "C"};
class A {
protected:
m_Type;
public:
ClassType Type() { return m_Type}
...
...
};
class B : public A {
otherMemberFunctions();
}
class C : public A {
otherMemberFunctions();
}
void WhatType(vector<A*>* candidates){
vector<B*> b_candidates(0);
vector<C*> c_candidates(0);
for(int i = 0; i < candidates->size(); i++){
if(candidates->at(i)->Type() == B ){
B* b = (B*) candidates->at(i);
b_candidates(b);
}
//Same idea for Object C
}
}
I would then use WhatType(vector<A*>* candidates) as follows
vector<B*>* b_example
WhatType((vector<A*>*) b_exmaple)
When I have filled the new vector b_candidates in the function WhatType. Will I still have access to the member functions in the B object or will I only have the access to the member functions in the base class A?
I am confused to what happens with the object when I change the type of the object.
Here
WhatType((vector<A*>*) b_exmaple)
and here
B* b = (B*) candidates->at(i);
When you receive a pointer to a polymorphic object you have two types: the "static" type of the object, which, in your case, will be A *, and its "dynamic" or "real" type, that depends on what was actually assigned to it.
Casting your A * to B * forces the compiler to consider that pointer as a pointer to B; this is safe as long as you actually know that that pointer is actually a pointer to B, otherwise the compiler will start writing nonsensical code (invoking B methods on data of another type).
The checks you are trying to implement are a homegrown version of RTTI, which is a mechanism that allows you to know which is the "real type" of a pointer or a reference to a polymorphic class, and to perform that kind of casts safely. Check out typeid and dynamic_cast on your C++ manual for more info about it. (Incidentally, IIRC dynamic_cast is not only for safety in case the dynamic type is wrong, but it may perform also some extra magic on your pointer if you use it in complicated class hierarchies; so, avoid C-style casting for polymorphic classes)
By the way, in general it's considered "code smell" to have to manually check the "real type" of the pointer in order to cast it and use its methods: the OOP ideal would be being able to do the work only though virtual methods available in the base class.
Big warning: RTTI works only on polymorphic classes, i.e. classes that have at least one virtual method. On the other hand, if you are building a class hierarchy where objects are being passed around as pointers to the base class you'll almost surely want to have a virtual destructor, so that's no big deal.
Since you cast to B*, you will have access to B's members.
The actual type of the objects does not change, of course, but if you only have a pointer (or reference) to the base class you can not access fields specific to the sub-classes.
What you can do to access sub-class fields is to use dynamic_cast to cast it to the sub-class:
A *a = new B; // We cant reach the members of class B in a
B *b = dynamic_cast<B *>(a); // But now we have a proper pointer to B
Ok, so if you had an object of type B instantiated on the heap and held by a pointer of type A. you can only see type A's member functions, to access type B's member functions you have to static_cast<B*> which is what the ... "(B*)" ... is doing.
dynamic cast is better as it will return a null if the conversion is not possible. but of course it happens a run-time so there's a penalty.
As B and C are À derived, a vector<B *> and vector<C *> contains A base class objects. If you ensure to set your A::m_Type attribute in your constructor, you will no have problems:
enum ClassType {'B', 'C'}; // see I modified your definition
class A {
protected:
ClassType m_Type;
public:
ClassType Type() { return m_Type};
...
...
};
class B : public A {
public:
B() : m_Type('B') {}
....
};
Using this, you will check without problems your B and Cobjects. After that, as you are casting base objects to derived ones, you will have fully access to their public methods and attributes.

Conversion from void* to the pointer of the base class

I have some hierarchy: base, derived classes and some structure storing user data as void*. That void can store both Base and Derived classes pointers. Main problem that I do not know what is stored there base or derived pointer.
class Base
{
public:
int type;
};
class Derived: public Base
{};
Base* base;//init base pointer
Derived* derived;//init derived pointer
void* base_v = base;
void* derived_v = derived;
//void pointers are correct. They point to base and derived variables.
//try to get type field after converting pointers back
Derived* d_restored = (Derived*)derived_v;//d_restored correct
Base* b_restored = (Base*)base_v;//b_restored correct
Base* d_restored_to_base = (Base*)derived_v;// INCORRECT
How to convert void* to get [type] field for both pointers?
Thanks in advance.
void*'s can only be converted back to their original type. When you store a Derived* in a void*, you can only cast back to Derived*, not Base*.
This is especially noticeable with multiple inheritance, as your derived object might not necessarily be at the same address as your base. If you really need to store things (and retrieve things) with void*, always cast to the base type first, so you have a stable way of getting the object back:
#include <iostream>
struct base { int type; };
struct intruder { int iminyourclassstealingyourbase; };
struct derived : intruder, base {};
int main()
{
derived d; d.type = 5;
void* good = (base*)&d;
void* bad = &d;
base* b1 = (base*)good;
base* b2 = (base*)bad;
std::cout << "good: " << b1->type << "\n";
std::cout << "bad: " << b2->type << "\n";
}
If you then want to go back to the derived type, use a dynamic_cast (or static_cast if you're guaranteed it has to be of the derived type.)
When you use multiple inheritance, the resulting object is internally acting much like a composite, conceptually something like this:
struct Derived {
Base1 b1;
Base2 b2;
};
You will get different addresses for your instance of Derived depending on whether you cast it to Base1 or Base2. So, you can't reliably do what you want to do. You'll need to keep a pointer to one of the involved types, and use dynamic_cast
Alternatively, you could make your own rules - saying that you always store the address of your instance casted to a specific base class, and always cast back to this base class. This is very error-prone, and I'd strongly recommend that you try to store a pointer to a common base class if at all possible.
If you know it's a derived pointer and you want to get a base pointer, you can do this:
Base* d_restored_to_base = (Base*)(Derived*)derived_v;
You will find that the Base* points to a different location than the Derived*, so the intermediary cast is required.
Use dynamic_cast, it can dynamically tell you if the pointer points to a Base object or not.

dynamic_cast from "void *"

According to this, void* has no RTTI information, therefore casting from void* is not legal and it make sense.
If I remember correctly, dynamic_cast from void* was working on gcc.
Can you please clarify the issue.
dynamic_cast works only on polymorphic types, i.e. classes containing virtual functions.
In gcc you can dynamic_cast to void* but not from:
struct S
{
virtual ~S() {}
};
int main()
{
S* p = new S();
void* v = dynamic_cast<void*>(p);
S* p1 = dynamic_cast<S*>(v); // gives an error
}
In 5.2.7 - Dynamic cast [expr.dynamic.cast] it says that for dynamic_cast<T>(v):
If T is a pointer type, v shall be an rvalue of a pointer to complete class type
If T is a reference type, v shall be an lvalue of a complete class type (thanks usta for commenting on my missing this)
...
Otherwise, v shall be a pointer to or an lvalue of a polymorphic type
So, no, a (void*) value is not allowed.
Let's think about what your request might mean: say you've got a pointer that's really to a Derived1*, but the code dynamic_cast-ing only knows it's a void*. Let's say you're trying to cast it to a Derived2*, where both derived classes have a common base. Superficially, you might think all the pointers would point to the same Base object, which would contain a pointer to the relevant virtual dispatch table and RTTI, so everything could hang together. But, consider that derived classes may have multiple base classes, and therefore the needed Base class sub-object might not be the one to which the Derived* - available only as a void* - is pointing. It wouldn't work. Conclusion: the compiler needs to know these types so it can perform some adjustment to the pointers based on the types involved.
Derived1* -----> [AnotherBase]
[[VDT]Base] <-- but, need a pointer to start of
[extra members] this sub-object for dynamic_cast
(Some answers talk about the need for the pointer you're casting from to be of a polymorphic type, having virtual functions. That's all valid, but a bit misleading. As you can see above, even if the void* is to such a type it still wouldn't work reliably without the full type information, as the real problem is that void* is presumably pointing to the start of the derived object, whereas you need a pointer to the base class sub-object from which the cast-to type derives.)
It is true that void* can't be dynamically_casted from.
You are probably mis-remembering.
With g++ 4.5 and the following code
struct A {
virtual ~A();
};
int main() {
A a;
void *p = &a;
A* pa = dynamic_cast<A*>(p);
}
I get the following error:
cannot dynamic_cast 'p' (of type 'void*') to type 'struct A*' (source is not a pointer to class)
I guess you confuse with dynamic_cast to void*. That is legal and obtains the pointer to the most derived class object.
dynamic_cast from void* is illegal - the type casted from must be polymorphic - contain at least one virtual function (virtual destructor counts too).
To add to Tony's nice answer, this little code snippet helps me for some reason. First, we establish a simple hierarchy. Then, we see if dynamic_cast can "survive" a static_cast. Before this experiment I thought "the run time type information is there, dynamic cast should figure it out." Now I realize "dynamic_cast must have to look up its information based on some tables the compiler is aware of, so it can't have some magical power."
#include <iostream>
#include <cassert>
using namespace std;
class A {
protected:
virtual void foo() { cout << "A" << endl; }
};
class B1 : public A {
private:
virtual void foo() override { cout << "B1" << endl; }
};
class B2 : public A {
public:
virtual void foo() override { cout << "B2" << endl; }
};
int main(int argc, char **argv) {
B1 b1;
// undefined behavior even though dynamic_cast didn't return null
dynamic_cast<B2*>(
static_cast<B2*>(
static_cast<A*>(&b1)))->foo();
// dynamic_cast returns null here though
assert (!dynamic_cast<B2*>
(static_cast<A*>
(static_cast<B2*>
(static_cast<A*>(&b1)))));
}
You can cast a pointer to polymorphic type to void *, but not vice versa.

Static vs dynamic type checking in C++

I want to know what are static and dynamic type checking and the differences between them.
Static type checking means that type checking occurs at compile time. No type information is used at runtime in that case.
Dynamic type checking occurs when type information is used at runtime. C++ uses a mechanism called RTTI (runtime type information) to implement this. The most common example where RTTI is used is the dynamic_cast operator which allows downcasting of polymorphic types:
// assuming that Circle derives from Shape...
Shape *shape = new Circle(50);
Circle *circle = dynamic_cast<Circle*> shape;
Furthermore, you can use the typeid operator to find out about the runtime type of objects. For example, you can use it to check whether the shape in the example is a circle or a rectangle. Here is some further information.
C++ has very little support for dynamic type checking. One way is through dynamic_cast and other is through type id. Both can be used only when RTTI support is enabled in compiler.
TYPE& dynamic_cast<TYPE&> (object);
TYPE* dynamic_cast<TYPE*> (object);
The dynamic_cast keyword casts a datum from one pointer or reference type to another, performing a runtime check to ensure the validity of the cast.
If you attempt to cast to pointer to a type that is not a type of actual object, the result of the cast will be NULL. If you attempt to cast to reference to a type that is not a type of actual object, the cast will throw a bad_cast exception.
Make sure there is at least one virtual function in Base class to make dynamic cast work.
// expre_typeid_Operator.cpp
// compile with: /GR /EHsc
#include <iostream>
#include <typeinfo.h>
class Base {
public:
virtual void vvfunc() {}
};
class Derived : public Base {};
using namespace std;
int main() {
Derived* pd = new Derived;
Base* pb = pd;
cout << typeid( pb ).name() << endl; //prints "class Base *"
cout << typeid( *pb ).name() << endl; //prints "class Derived"
cout << typeid( pd ).name() << endl; //prints "class Derived *"
cout << typeid( *pd ).name() << endl; //prints "class Derived"
delete pd;
}
Assume you have:
class A {};
class B:A {};
A* a = new B();
B* b = new B();
For the static type, you look at how the variable is declared.
A* a = ...
B* b = ...
So the static type of a is A* (or to put it another way, the static type of *a is A).
And the static type of b is B* (or to put it another way, the static type of *b is B).
Note that a and b have a static type that is fixed by it's declaration - it doesn't matter what you put in them, they will keep the same static type. ("static" means "unchanging").
For the dynamic type, you look at what happens to be in the variable right now.
a = new B();
b = new B();
So the dynamic types of a and b are both B* (or to put it another way, the dynamic types of *a and *b are both B).
Note that the dynamic type can change - if you did a = new A() then they dynamic type of a just changed to A*. Sometimes you don't know what the dynamic type is - e.g. if you do a = somefunc() then a might have dynamic type A*, B* or even C* (if some code you haven't seen defines C as a subclass of A or B).
If A had a virtual method on it, then you could use dynamic_cast to figure out what the dynamic type is. (Typically, if you're using this sort of code, you want to be able to do delete a; for that to work A's destructor has to be virtual. And making A's destructor virtual is enough for dynamic_cast to work).
There are multiple types of casts available in C++.
The most common would be to use static_cast in order to cast a variable from one type of pointer to another. However, you can also use dynamic_cast, which will check to make sure (at runtime) that the pointers are of the correct type. With dynamic_cast, if the pointer is not of the right type, at runtime, it will return 0 instead.
// Assume these classes exist
// class A
// class B
// class C : B
C* c = new C();
A* a = new A();
B* b = static_cast<B*>(a); // this will work!
b = dynamic_cast<B*>(a); // b == NULL
b = dynamic_cast<B*>(c); // b is valid
Static type checking is type checking that is done at compile time. This is the only type of type checking that C++ does. Dynamic type checking is type checking done at run time. This is usually seen in dynamic interpreted languages, but is less common in compiled languages. Last I checked, C++ doesn't do any sort of dynamic type checking.
Edit: Apparently I'm out of date. See Reed's comment below.