#include<typeinfo>
#include<iostream>
usingnamespace std;
class Base{
friendbooloperator==(const Base&, const Base&);
public:
Base(int i) :base(i){}
virtual ~Base() = default;
int base;
protected:
virtualbool equal(const Base&) const;
};
class Derived :public Base{
public:
Derived(int i,int j) :Base(i),derived(j){}
int derived;
protected:
bool equal(const Base&) const;
};
booloperator==(const Base &lhs, const Base &rhs)
{
returntypeid(lhs) == typeid(rhs) && lhs.equal(rhs);
}
bool Derived::equal(const Base &rhs) const
{
auto r = dynamic_cast<const Derived&>(rhs);
return derived == r.derived && (Base::equal(rhs));
}
bool Base::equal(const Base &rhs) const
{
return base == rhs.base;
}
int main(){
Base b1(1), b2(2);
Derived d1(1, 11), d2(2, 22);
if (d1 == b1)
cout << "Yes";
else
cout << "No";
cout << endl;
Derived &d3 = dynamic_cast<Derived&>(d1);
cout << d3.derived;
//error
//Derived &d4 = dynamic_cast<Derived&>(b1);
//cout << d4.derived;
system("pause");
}
I have two question.
Q1:
Why the d4.derived is an error? The dynamic_cast doesn't construct the Derived member value? Because I think it could be the default value.
Q2:
If the d4.derived is an error now.
Why the function "bool Derived::equal(const Base &rhs) const" works correctly?
I mean in the main function:
"if(d1==b1)"
the b1 is dynamic_cast, and is compared by the expression "derived == r.derived",
but the r.derived supposed to be invalid.