c++ inheritance

Consider this:
1
2
class A{}
class B : public A{}


if i have this scenario, i am ok
1
2
A *a = new B;
B *b = (A *) b;


what about this
1
2
3
A a;
A *ap = &a;
B *bp = dynamic_cast<B *>(ap);


Is the second case OK?
Or is there any other way i can perform this cast, if i want
a derived type instance, and the reference to the base is not created by the new operator?

Last edited on
No, it is not. The dynamic_cast will fail, because the underlying object is not of type B at runtime.
This should work, however:

1
2
3
B b;
A* ap = &b;
bp = dynamic_cast<B*>(ap);
Last edited on
You can use static cast for this.
my example:

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
#include <iostream>
#include <stdio.h>
using namespace std;

class Base {
public:
	int value1;
	// default constructor:
	Base () {
		value1 = 0;
	}
	
	// notice:to perform a dynamic cast on a type, the type
	// MUST HAVE AT LEAST ONE VIRTUAL MEMBER
	// if the following method is commented out,we will get
	// a compilation error caused by dynamic_cast in main();
	virtual void setValue(int newValue) {
		value1 = newValue;
	}
};

class Derived: public Base {
public:
	int value2;
	// default constructor:
	Derived () {
		value2 = 0;
	}
};

int main () {
	Derived *derived = new Derived;
	derived->value2 = 20;
	Base *base = new Base;
	base->value1 = 10;
	cout << "value1 of base is " << base->value1 << endl;
	
	// now try assigning Derived to Base:
	// Derived *derived = (Base*)derived;
	// OR
	// Derived *derived = base;
	// you will get a compilation error
	
	// we can do the following line for sure
	base = derived;
	
	// as long as there is at least one virtual member is class Base,
	// we can do the following dynamic cast
	derived = dynamic_cast<Derived *>(base); 
	
	delete base;
	delete derived;
	return 0;
}


as for why there has to be at least one virtual member in class Base in order to perform dynamic cast,this is due to the Run-TIme Type Identification(RTTI).More info can be found here:
http://en.wikipedia.org/wiki/Run-time_type_information


I doubt you can do the following:
1
2
A *a = new B;
B *b = (A *) b;
1
2
3
Derived *derived = new Derived;
Base *base = new Base;
base = derived; //memory leak 

You can use static cast for this.


static_cast is not typesafe.

You can use static cast for this.


static_cast is not typesafe. It is also not significantly faster than dynamic_cast (dynamic_cast should not take more than 1-2 CPU cycles).
Topic archived. No new replies allowed.