0

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!
scohe001
  • 15,110
  • 2
  • 31
  • 51
java
  • 1,165
  • 1
  • 25
  • 50

1 Answers1

0

You are passing the pointer by value, this means that the value is copied, and in the function you only modify the copy. Modifying a copy will of course not modify the original.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621