I'm having trouble getting the right operator to be accessed using polymorphism.
The code below is a simple representation of the problem, but it should get the point across.
//Horse.h
#ifndef HORSE_H_INCLUDED
#define HORSE_H_INCLUDED
#include <iostream>
#include <string>
class Horse
{
public:
Horse() {}
Horse(int age) : itsAge(age) {}
virtual ~Horse() {}
virtual void operator=(const Horse& rHorse) {itsAge = rHorse.itsAge; std::cout<<"Horse operator= ..."<<std::endl;}
int GetAge() const {return itsAge;}
void SetAge(int age) {itsAge = age;}
virtual std::string Speak() = 0;
protected:
int itsAge;
};
#endif // HORSE_H_INCLUDED
//Pony.h
#ifndef PONY_H_INCLUDED
#define PONY_H_INCLUDED
#include "Horse.h"
class Pony : public Horse
{
public:
Pony() {}
Pony(int age) {itsAge = age;}
~Pony() {}
void operator=(const Pony& pony) {itsAge = pony.itsAge;std::cout<<"Pony operator= ..."<<std::endl;}
std::string Speak() {return "I'm a pony.";}
};
#endif // PONY_H_INCLUDED
//Main.cpp
#include <iostream>
#include "Pony.h"
using namespace std;
int main()
{
Pony pony(10);
Horse* pHorse = new Pony;
*pHorse = pony;
cout << pHorse->Speak() << endl << "It's age is " << pHorse->GetAge() << endl;
delete pHorse;
return 0;
}
Output of the program:
Horse operator= ...
I'm a pony.
It's age is 10
The problem being the first line in the output. The horse operator is called instead of the pony operator.
In this program, there's no difference. But in the application I'm working on, this is a problem since there's several classes, with different member variables.
I havn't really found a way to get around this other than defining a function virtual void Horse::operator=(const Pony&)
which doesn't seem like a good solution.
Any ideas to have the right operator called are welcome!