Suppose in C++, if we have a base class Base and a child class derived:
class Base{
protected:
int x_base;
};
class Derived : public Base {
public:
int x_prot;
};
Than in the main we can create a pointer to the base class and let it point to a derived class object:
Base *b;
b=new Derived;
But this instead is not allowed:
Derived *b;
b=new Base;
I would have thought the opposite.
When we call Base* b
we are saying to the code that b
will be a pointer to an object to class Base
. In the example, he will be ready to allocate space for x_base
(but not for x_prot
). So we should not be able to use the pointer of the base class to point to an object of the child class.
Where is the error in my reasoning?