#include <stdio.h>
#include <stdlib.h>
#include <iostream>
class container {
private:
int mydata;
public:
/* costructor */
inline container (int number) {
mydata = number;
}
/* destructor */
inline ~container() {
}
virtualchar* getType() = 0;
inlineint getmydata(){ return mydata; }
};
class a : public container {
public:
/* costructor */
inline a (int number) : container(number) {
}
inlinechar* getType(){
return"CLASS A";
}
};
class b : public container {
public:
int bdata;
/* costructor */
inline b (int number, int bnumber) : container(number) {
bdata = bnumber;
}
inlinechar* 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.