I am writing a program for a pointer to a Derived class. Here is my code
#include <iostream> using namespace std; class base { int i; public: void set_i(int num) { i=num; } int get_i() { return i; } }; class derived: public base { int j; public: void set_j(int num) {j=num;} int get_j() {return j;} }; int main() { base *bp; derived d[2]; bp = d; d[0].set_i(1); d[1].set_i(2); cout << bp->get_i() << " "; bp++; cout << bp->get_i(); return 0; }
The program displays 1 correct value and another garbage value, because
by. ++;
increases the pointer to the next object of the base class type , but not to the derived class type .
we can correctly display the answer by writing
> bp =& d[0]; bp1=&d[1]; d[0].set_i(1); d[1].set_i(2);
but then we need to assign 2 pointers. Similarly, if we need to accept 100 values, we need to assign 100 pointers. This is not good.
My question is, can we show the value of an array with a single pointer?
source share