S
Stuart Brockman
Hi,
I don't quite get what is going on in this code example:
---------------------------
#include <iostream>
using namespace std;
class Base{
public:
virtual void Test(){
cout << "Base" << endl;
}
virtual bool operator==(const Base &other){
cout << "Base Comparison" << endl;
return false;
}
};
class Derived : public Base{
public:
void Test(){
cout << "Derived" << endl;
}
bool operator==(const Derived &other){
cout << "Derived Comparison" << endl;
return true;
}
};
int main(int argc, char** argv) {
Base a; //Create a base object
a.Test(); //Outputs "Base" as expected
Derived b, c; //Create two derived objects
b.Test(); //Outputs "Derived" as expected
if(b==c) cout << "True" << endl; //Does derived comparison and
returns true as expected.
Base *d=&b, *e=&c; //Create two base pointers to derived objects
d->Test(); //Outputs "Derived" as expected
if(*d==*e) cout << "True" << endl; //Does base comparison and
returns false!?
return 0;
}
----------------------------
The output is:
Base
Derived
Derived Comparison
True
Derived
Base Comparison
Notice, that the line "d->Test()" works correctly, but the comparison
on the next line does not. The compiler (g++ (GCC) 4.2.3 (Ubuntu
4.2.3-2ubuntu7) ) seems to be ignoring the virtual-ness of
Base:perator== . Is this correct? Have I made a mistake?
I don't quite get what is going on in this code example:
---------------------------
#include <iostream>
using namespace std;
class Base{
public:
virtual void Test(){
cout << "Base" << endl;
}
virtual bool operator==(const Base &other){
cout << "Base Comparison" << endl;
return false;
}
};
class Derived : public Base{
public:
void Test(){
cout << "Derived" << endl;
}
bool operator==(const Derived &other){
cout << "Derived Comparison" << endl;
return true;
}
};
int main(int argc, char** argv) {
Base a; //Create a base object
a.Test(); //Outputs "Base" as expected
Derived b, c; //Create two derived objects
b.Test(); //Outputs "Derived" as expected
if(b==c) cout << "True" << endl; //Does derived comparison and
returns true as expected.
Base *d=&b, *e=&c; //Create two base pointers to derived objects
d->Test(); //Outputs "Derived" as expected
if(*d==*e) cout << "True" << endl; //Does base comparison and
returns false!?
return 0;
}
----------------------------
The output is:
Base
Derived
Derived Comparison
True
Derived
Base Comparison
Notice, that the line "d->Test()" works correctly, but the comparison
on the next line does not. The compiler (g++ (GCC) 4.2.3 (Ubuntu
4.2.3-2ubuntu7) ) seems to be ignoring the virtual-ness of
Base:perator== . Is this correct? Have I made a mistake?