A Base Class pointer can point to a derived class object. Why is the vice-versa not true?
That thread says that we can't make the derived class point to base class because the derived class may not have access to all the members of base class.
The same is true vice versa also. The base class won't even have access to the members which are specific to derived classes.
#include <iostream>
using namespace std;
class BaseClass
{
public:
virtual void baseFx();
};
void BaseClass::baseFx()
{
std::cout << "From base virtual function\n";
}
class DerivedClass : public BaseClass
{
public:
void baseFx();
void h() { std::cout << "From derived class. h()\n"; }
};
void DerivedClass::baseFx()
{
std::cout << "From derived virtual function\n";
}
int main()
{
BaseClass* objBaseclassB = new DerivedClass();
objBaseclassB->baseFx (); // Calls derived class's virtual function.
objBaseclassB->h(); // error: 'class BaseClass' has no member named 'h'.
return 0;
}
So, why is the restriction only for derived class? Why is this not allowed considering the above logic?
DerivedClass* objBaseclassC = new BaseClass();