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 is displaying 1 correct value and other garbage value because
bp++;
is incrementing the pointer to point to next object of class base type but not of class derived type.
we can display answer correctly by writing
> bp =& d[0];
bp1=&d[1];
d[0].set_i(1);
d[1].set_i(2);
but then we have to assign 2 pointers .Similarly if we have to take 100 values then we have to assign 100 pointers.That is not good.
My question is that can we show the value of array by single pointer ?