static_cast Confusion

Greetings,

I can not seem to get my brain wrapped around static_cast. Can you help me understand what is wrong in ANY of my following three examples:

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
54
class RSet 
{
	public:
		int Test();
}

class DSet : RSet
{
}


DSet MyFirst()
{
	RSet goodval;
	goodval = GetValue();
	cout << goodval.Test();					// 3

	DSet badval;
	badval = static_cast<DSet&>(goodval);
	cout << badval.Test();					// 0
	
	return badval;
} 

DSet MySecond()
{
	RSet goodval;
	goodval = GetValue();
	cout << goodval.Test();					// 3

	Rset* rcopy = new DSet();
	rcopy = &goodval;
	
	DSet* dcopy = static_cast<DSet*>(rcopy);
        DSet fcopy = *dcopy;
        cout << fcopy.Test();					// 0
    
        return fcopy;
}

DSet MyThird()
{
	DSet badval;
	RSet& goodval = badval;
	
	RSet goodval;
	goodval = GetValue();
	cout << goodval.Test();					// 3
	
	DSet* dcopy = static_cast<DSet&>(goodval);
	cout << dcopy.Test();					// 0
	
        return dcopy;
}


In both cases Test() should be equal to 3, but my cast statements don't pass the same value.

Thanks in advance.
Last edited on
That doesn't compile. But if the pseudocode in the beginning is any indication, DSet is derived from RSet, so accessing an RSet object through a reference to DSet is undefined.
Last edited on
Topic archived. No new replies allowed.