Modify a member by static_cast cause segmentation fault

I have the next program: if I comment the assignation mNum=num; or mCh=ch the segmentation fault don't exist.

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <vector>
class Base{

public:
	Base(){};
	~Base();
	void setNum(int num){
		mNum=num;
	    }
	int getNum();

protected:
	int mNum;
};

class Derived:public Base{

public:
	Derived(){};
	~Derived();
	void setChar(char ch){
		mCh=ch;
	}
	char getChar();

protected:
	int mCh;
};

class One{
public:
	One(int type){
		 switch(type) {
		        case 0:
		            mBase= new Base();
		            break;
		        case 1:
		            mBase= new Derived();
		            break;
	    }


	};

	void SetNumber(){
		   Base* b = static_cast<Base*>(mBase);
		         b->setNum(1);

	};
	void SetChar(){
		   Derived* d = static_cast<Derived*>(mBase);
		       d->setChar('r');

	};
	~One();
private:
	 Base *mBase;

};

class Two{
public:
	Two(){};
	~Two();
	void print1(){
		mOnes.push_back(NULL);
		mOnes.push_back(NULL);

		mOnes[0]=new One(1);
		mOnes[1]=new One(2);

		mOnes[0]->SetNumber();
		mOnes[1]->SetChar();



	};
private:
	 std::vector<One*> mOnes;


};

int main(){

	Two *mTwo=new Two();
	mTwo->print1();

}
Last edited on
Please enclose your code in code tags, so that it's more readable. Edit your post, and use the "<>" button to the right of the edit window.
You pass the value 2 to the One constructor when it expects 0 or 1.
Topic archived. No new replies allowed.