A function GetCarPrice()
has a return type of a class Money
where the function is declared, and this method is not declared within Money
, meaning it's not a member function of this class.
Later, I derive another class from Money
, defined as Dollar
, with some additional attributes and methods.
Now, I want to return Dollar
type object when using the function GetCarPrice()
inside the main function, keeping the declaration of this function the same.
Here is a brief pseudo code:
class Money {...}; `
class Dollar: public Money {...};
Money* GetCarPrice () {...};
int main()
{
Dollar* D1;
...
D1 = GetCarPrice(); // Here I get error: invalid conversion from Money to Dollar
...
}
Is there any way to do this in C ?
N.B. I am new to this platform, please pardon my mistakes. Please do not close it, I need help. TIA.
CodePudding user response:
Just create a Dollar instance and return the pointer of it in the GetCarPrice().
If there are some legacy code that creates a Money instance and you want to keep it, you should convert the object like this.(If the Money class has a copy constructor, it will be easy because you can call it at the constructor of the Dollar.)
class Dollar : public Money {
...
Zzz zzz;
public:
Dollar(const Money &money) : Money(money) {
zzz = transform_xxx_yyy_to_zzz(money.xxx, money.yyy);
...
}
}
Money* GetCarPrice ()
{
...
Money* money = ...;
if (...) { // If you should convert to a Dollar.
Dollar* dollar = new Dollar(*money);
delete money; // This prevents a memory leak.
return dollar;
}
return money;
}
And you can safely cast a Money pointer to a Dollar pointer like this.
Money* m = GetCarPrice();
Dollar* d = dynamic_cast<Dollar*>(m);
if (d) {
// the m is actually a Dollar, so do whatever with the d.
}