A base pointer to access derived objects : Pointer Object « Pointer « C++






A base pointer to access derived objects

A base pointer to access derived objects

#include <iostream>
using namespace std;
class BaseClass {
  int i;
public:
  void setInt(int num) { 
    i = num; 
  }
  int getInt() { 
    return i; 
  }
};
class derived: public BaseClass {
  int j;
public:
  void setJ(int num) { 
     j = num; 
  }
  int getJ() { 
     return j; 
  }
};
int main()
{
  BaseClass *baseClassPointer;
  derived d;
  baseClassPointer = &d;     // BaseClass pointer points to derived object
                             // access derived object using BaseClass pointer
  baseClassPointer->setInt(10);
  cout << baseClassPointer->getInt() << " ";

  return 0;
}

           
       








Related examples in the same category

1.Incrementing and decrementing an object pointer. Incrementing and decrementing an object pointer.
2.When a pointer is incremented, it points to the next element of its type
3.Pointers to ObjectsPointers to Objects