Class father has no member

Hi all, I'm working on a project and i have to do 3 simple classes but I have this problem:

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

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

class container {

	private:
		int mydata;

	public:
		/* costructor */
		inline container (int number) {
			mydata = number;
		}

		/* destructor */
		inline ~container() {
		}

		virtual char* getType() = 0;
		
		inline int getmydata(){ return mydata; }

};

class a : public container {

	public:
		
		/* costructor */
		inline a (int number) : container(number) {

		}


		inline char* getType(){
			return "CLASS A";
		}

};

class b : public container {


	public:
		int bdata;

		/* costructor */
		inline b (int number, int bnumber) : container(number) {
			bdata = bnumber;
		}

		inline char* getType(){
			return "CLASS B";
		}

};


int main(int argc, char **argv){
	
	container * mycont = new a(10);

	if( strcmp( mycont->getType(), "CLASS A") == 0 )
		printf("%d", mycont->getmydata());	

	if( strcmp( mycont->getType(), "CLASS B") == 0 )
		printf("%d", mycont->bdata);	
		

	return 0;
}


when compile it returns:

1
2
3
user@laptop:~/Desktop$ g++ example.cpp -o example
example.cpp: In function ‘int main(int, char**)’:
example.cpp:68: error: ‘class container’ has no member named ‘bdata’


This because I have to use the father class but the variable exist only in the son class 'b' ( I'm sure I'm reading the b son class because there's the IF).
I can't put bdata in the father class, because this variable must is not visible by a.

Any idea ?? thanks for help and sorry for my bad english
Hey.
You need an downcast from "container" to b.
If you're realy know that in this case mycont is in real a class of type B, than you can use a classic C static cast.
In your code, i would use a dynamic_cast. If the cast is possible it will return the new pointer, else NULL, so try this:

1
2
3
4
5
6
container * mycont = new a(10);
a * mya = dynamic_cast<a*>(mycont);
b * myb = dynamic_cast<b*>(mycont);

if (mya) printf("%d", mya->getmydata());	
if (myb) printf("%d", myb->bdata);	


You see - there is no need for a getType. Beware a little bit, because dynamic_casts maybe slower like a static_cast.

Adler

It works !! Thanks a lot !!
Topic archived. No new replies allowed.