Question about dynamic_cast in C++ Primer 5th

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<typeinfo>
#include<iostream>
using namespace std;

class Base{
	friend bool operator==(const Base&, const Base&);
public:
	Base(int i) :base(i){}
	virtual ~Base() = default;
	int base;
protected:
	virtual bool 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;
};

bool operator==(const Base &lhs, const Base &rhs)
{
	return typeid(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.

Thank you for your help and patience
Last edited on
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.


For the same reason
1
2
    int a ;
    double &b = a; 

is an error.

The types do not match. An int is not a double and a Base is not a Derived.



Why the function "bool Derived::equal(const Base &rhs) const" works correctly?
I mean in the main function:
"if(d1==b1)"


Here, Derived::equal is not called. The operator== on line 23 is called and that ensures the function you are asking about is not called.

An illustration that Derived::equal is not called: http://ideone.com/mgnea1
Last edited on
Thank you again! XD
Topic archived. No new replies allowed.