I'm trying to write a Swap function to swap 2 different types of objects of an array in C++. How can I do that? (I prefer using pointer to solve this problem)
I've tried to use template classes to swap 2 objects because the types of object are different from others and when looping through the array, I don't know which objects that one element belongs to.
I have 3 classes (Object_A, Object_B and Object_C) as below:
class Object_A : public base_class
{
private:
int workingTime;
int relaxTime;
float salary;
public:
Object_A();
virtual ~Object_A();
float Cal_Salary();
int getWorkingTime() const;
void setWorkingTime(int workingTime);
int getRelaxTime() const;
void setRelaxTime(int relaxTime);
float getSalary() const;
void setSalary(float salary);
};
class Object_B : public base_class
{
private:
float income;
public:
Officer();
virtual ~Officer();
float getIncome() const;
void setIncome(float income);
};
class Object_C : public base_class
{
private:
std::string role;
float roleCoef;
float bonus;
public:
Manager();
virtual ~Manager();
float Cal_Bonus();
const std::string& getRole() const;
void setRole(const std::string& role);
float getRoleCoef() const;
void setRoleCoef(float roleCoef);
float getBonus() const;
void setBonus(float bonus);
};
// I tried to write SwapValues func
template<class T, class U>
void SwapValues(T* a, U* b)
{
T temp = a;
a = b;
b = temp;
}
I have an array with base_class type to store some elements of three objects above (Object_A, Object_B and Object_C). However when I want to swap one element of Object_A to one of Object_C with SwapValues() func, it doesn't work!
Thanks a lot for your help.