If I am NOT using a reference to a pointer when sending the base-pointer to another class constructor - and in this class binding the basepointer to a derived object of the base - the basepointer returns NULL.
Simply - what is the reason for this?
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() = 0;
};
class Sub1 : public Base {
public:
void print() {
cout << "I am allocated!\n";
}
};
class App {
public:
App(Base *b) {
b = new Sub1;
}
};
int main() {
Base *b;
b = NULL;
App app(b);
if (b != NULL)
b->print();
else
cout << "Basepointer is NULL\n";
return 0;
}
The crucial part here is the signature of the App-class constructor
when not using a reference to the basepointer i.e
App(Base *b)
the output is:
Basepointer is NULL
And when using a reference to the base-class i.e.
App(Base *&b)
the output is:
I am allocated!