I understood why a base class pointer is made to point to a derived class object. But, I fail to understand why we need to assign to it, a base class object, when it is a base class object by itself.
Can anyone please explain that?
#include <iostream>
using namespace std;
class base {
public:
virtual void vfunc() {
cout << "This is base's vfunc().\n";
}
};
class derived1 : public base {
public:
void vfunc() {
cout << "This is derived1's vfunc().\n";
}
};
int main()
{
base *p, b;
derived1 d1;
// point to base
p = &b;
p->vfunc(); // access base's vfunc()
// point to derived1
p = &d1;
p->vfunc(); // access derived1's vfunc()
return 0;
}
Because pointers by themselves cannot do anything.
A pointer has to point to a valid object so that you can make any use of it.
Why the above statement?
A step by step explanation will perhaps clear your doubt.
Step 1:
base *p;
Creates a pointer p
which can store the address of an object of class base
. But it is not initialized it points to any random address in memory.
Step 2:
p = &b;
Assigns the address of an valid base
object to the pointer p
. p
now contains the address of this object.
Step 3:
p->vfunc(); // access base's vfunc()
Dererences the pointer p
and Calls the method vfunc()
on the object pointed by it. i.e: b
.
If you remove the Step 2:, Your code just tries to Dereference a Uninitialized pointer and would cause a Undefined Behavior & most likely a crash.