Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How do we properly downcast an array of Base objects to their corresponding Derive type/object?

pseudocode:
Base b[] = { Derive1("dOne"), Derive2(2) }
print ((Derive1)b[0]).getSpecialMemFuncOfDerive1()
print ((Derive2)b[1]).getSpecialMemFuncOfDerive2()


What I have tried:

I have this kind of instantiation, and I tried to downcast it because my Base class didn't have a mem-func that I wanted to invoke.
C++
DeriveOne* deriveOne = new DeriveOne("dOne");
DeriveTwo* deriveTwo = new DeriveTwo(2);

Base* base[] = { deriveOne, deriveTwo };

std::cout << deriveOne->getStr() << std::endl;
std::cout << ((DeriveOne*)base)->getStr() << "\n\r"; //REM: it didn't work?
std::cout << "============\n\r";

std::cout << deriveTwo->getValue() << std::endl;
std::cout << ((DeriveTwo*)&base[1])->getValue() << "\n\r"; //REM: it didn't work?
std::cout << "============\n\r";

delete* base;
Posted
Updated 20-Jul-22 17:09pm
v4
Comments
Kumar Vikram 2022 20-Jul-22 12:14pm    
7054605622

1 solution

If the classes DeriveOne, DeriveTwo derive polymorphically from Base then you may use dynamic_cast, e.g.
C++
std::cout << (dynamic_cast <DeriveOne *> (base[0]))->getStr() << "\n\r";
otherwise, you may use reinterpret_cast, e.g.
C++
std::cout << (reinterpret_cast <DeriveOne *> (base[0]))->getStr() << "\n\r";
 
Share this answer
 
Comments
Phoenix Liveon 19-Jul-22 5:44am    
Hi, @CPallini, first of all THANK YOU VERY MUCH, I know this is a sufficient/effective solution, but is there a premitive/c-style casting way of doing it? For educational purpose, I'm eager to know what its look like.
CPallini 19-Jul-22 5:48am    
Yes, there is. It is the one you used.
Greg Utas 19-Jul-22 7:30am    
If you know the derived class, use static_cast. It has the same syntax as the ones that CPallini showed but has no overhead (dynamic_cast does) and isn't overkill (like reinterpret_cast, which should be avoided when possible).
Phoenix Liveon 19-Jul-22 7:38am    
Thanks, noted.
Phoenix Liveon 19-Jul-22 5:56am    
OK... So... C-language, technically do not support polymorphism? But there must be a proper/correct way? For now I will try to get enough enough information about these pre-define c++ casting operation. And thank so much again.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900