Kentucky88
May 4th, 2012, 04:16 AM
#include <iostream>
#include <map>
using namespace std;
class base {
protected:
int number;
public:
base() { number = 3; }
virtual void printNum() { cout << "Not the one class" << endl; }
};
class one : public base {
public:
one() { number = 1; }
void printNum() { cout << number << endl; }
};
int main()
{
base bse;
one uno;
bse = uno;
one* oneptr = dynamic_cast<one*>(&uno);
one* baseptr = dynamic_cast<one*>(&bse);
if(oneptr != NULL) cout << "Test 1 worked" << endl;
if(baseptr != NULL) cout << "Test 2 worked" << endl;
oneptr->printNum();
baseptr->printNum();
return 1;
}
Output:
Scratch.exe
Test 1 worked
1
Can someone explain why "Test 2 worked" was not printed in the output above? I know that if I had the instantiated the 'uno' object on the heap and was working with pointers instead of objects on the stack, the second dynamic cast would have worked. However, when I copy the uno object into bse, is the upcast necessitated by the need to make the superclass (one) fit in the space allocated for the base class (base)? If so, that would make sense (even though in this case, both objects should consume the same amount of space since the subclass does not introduce any new member variables). I still expected to see "Not the one class" print on the last line. Does anyone know why it did not print?
#include <map>
using namespace std;
class base {
protected:
int number;
public:
base() { number = 3; }
virtual void printNum() { cout << "Not the one class" << endl; }
};
class one : public base {
public:
one() { number = 1; }
void printNum() { cout << number << endl; }
};
int main()
{
base bse;
one uno;
bse = uno;
one* oneptr = dynamic_cast<one*>(&uno);
one* baseptr = dynamic_cast<one*>(&bse);
if(oneptr != NULL) cout << "Test 1 worked" << endl;
if(baseptr != NULL) cout << "Test 2 worked" << endl;
oneptr->printNum();
baseptr->printNum();
return 1;
}
Output:
Scratch.exe
Test 1 worked
1
Can someone explain why "Test 2 worked" was not printed in the output above? I know that if I had the instantiated the 'uno' object on the heap and was working with pointers instead of objects on the stack, the second dynamic cast would have worked. However, when I copy the uno object into bse, is the upcast necessitated by the need to make the superclass (one) fit in the space allocated for the base class (base)? If so, that would make sense (even though in this case, both objects should consume the same amount of space since the subclass does not introduce any new member variables). I still expected to see "Not the one class" print on the last line. Does anyone know why it did not print?