Mark wrote in message
<11**********************@i42g2000cwa.googlegroups .com>...
>
Andre Kostur wrote:
>"Mark" <mn*******@gmail.comwrote in news:1162340151.361660.142970
@f16g2000cwb.googlegroups.com:
I can't seem to get this subclass to upcast to a baseclass... see
comments below
#include <cstdlib>
#include <iostream>
#include "Base.h"
#include "Sub1.h"
using namespace std;
void f(Base* b){
cout << "ok";
}
int main(int argc, char *argv[]){
Sub1* s1;
Base* b;
f(s1); // how come I can do this
Because you're upcasting from a derived class to a base.
s1 = b; // but not this??
That's a downcast, not an upcast. You are casting (or attempting to)
from a base to a derived class. Can't be done implicitly.
system("PAUSE");
return EXIT_SUCCESS;
}
the compiler complains..
19 invalid conversion from `Base*' to `Sub1*'
and if you need the header files..
#ifndef SUB1_H
#define SUB1_H
#include "Base.h"
class Sub1 : public Base { public:
Sub1* clone();
};
#endif
#ifndef BASE_H
#define BASE_H
class Base{ public:
Base* clone();
};
#endif
help appreciated.
wait..what?
how is s1 = b; a downcast? i'm trying to make my subclass point to the
baseclass.. that moves it UP the hiearchy, no??
you're suggesting that b = s1; is an upcast?
could you perhaps elaborate a bit?
class shape {..... virtual ~shape(){} };
class circle : shape {.....};
Usually 'diagramed' like this:
|-------------|
| shape |
|-------------|
^
|
|-------------|
| circle |
|-------------|
Going from 'circle' to 'shape' is upcasting.
Going from 'shape' to 'circle' is downcasting.
A 'circle' knows it is a 'shape' [1], but a 'shape':
"Hey man, I must have been drunk, 'cause I don't know how many kids I got out
there, or what they look like! Can you give me a clue (down cast)[2]".
shape *sh;
circle *cr;
circle C1;
sh = &C1; // upcast
cr = dynamic_cast<circle*>( sh ); // downcast
if( cr ){
std::cout<<"OK"<<std::endl;
}
else{
std::cout<<"That wern't no circle, dude!!"<<std::endl;
}
--
Bob R
POVrookie