Base pointer to an object in derived class in C++

Generally a pointer cannot point an object of different type. However, a pointer from a base class can point to an object from a derived class provided the derived class is derived from this particular base class. But, it’s not true the other way round. A pointer from a derived class can’t point an object to a base class. Also, when a base pointer pointing an object in derived class only members imported from base class can be accessed and the members added by the derived class can’t be accessed.

For Example:

#include <iostream>

using namespace std;

class base {

int x;


void set_x(int n) { x=n; }

int get_x() { return x; }


class derived: public base {

int y;


void set_y(int n) { y=n; }

int get_y() { return y; }


int main()


base *p;

derived d;

p = &d;


cout << p->get_x() << ” “;

return 0;


Leave a Reply