Solved when to use casting in c++ instead class global pointer?
-
I have seen that we can access other class by taking global pointer in other class. And i also have seen that we can use that class by casting . so i want to know what i should prefer and when ?
for example for casting
this->pTransactionData = dynamic_cast<app::transaction::CustomTxnDataContainer*>(pTransactionData);
and example for class global pointer
TransactionDataContainer *pTransactionData = new TransactionDataContainer ;
-
@Qt-embedded-developer
These are two unrelated concepts, and are not interchangeable.dynamic_cast<Something *>
means you already have a pointer to the object, created elsewhere, and you just want to test whether it points to aSomething
here.new Something
means you are creating the object here, and receiving a pointer to it. -
@Qt-embedded-developer said in when to use casting in c++ instead class global pointer?:
and example for class global pointer
TransactionDataContainer *pTransactionData = new TransactionDataContainer ;Where is this code located?
If inside a class (this->pTransactionData suggests that), then it is not a global pointer."so i want to know what i should prefer and when ?" - I am not really sure I understand your question. Casting is only needed if the type of the pointer is not exact same as the type of the pointer you're assigning. And you can have a pointer to an instance of a class if you need to access it. So, all depends on your needs.
-
@Qt-embedded-developer
These are two unrelated concepts, and are not interchangeable.dynamic_cast<Something *>
means you already have a pointer to the object, created elsewhere, and you just want to test whether it points to aSomething
here.new Something
means you are creating the object here, and receiving a pointer to it. -
-
@Qt-embedded-developer said in when to use casting in c++ instead class global pointer?:
is it right for any type of casting ?
What do you mean?
https://en.cppreference.com/w/cpp/language/static_cast
https://en.cppreference.com/w/cpp/language/dynamic_cast -
global pointers to members of another glass are generally a bad idea because accessing the class without going thru the MOC can have undesired behaviour. inter-class comms should be via signal/slot rather than direct handle to the target class instance.