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 ?
Is it possible that a base class pointer pointing to a Derived class object in C++? Yes, it is possible. Next, we have called functions fun1, fun2, and fun3 with the help of pointer p.
When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002.
Let's see the example of incrementing pointer variable on 64-bit architecture. printf("Address of p variable is %u \n",p); p=p+1; printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incremented by 4 bytes.
I imagine the reason OP is trying to do this is so that he can have an array of objects which can be arbitrary derived instances of some base class, and iterate over them. If this is the case, you really need an array of pointers to your base class. Something like:
class Base { /* ... */ };
class Derived1 : public Base { /* ... */ };
class Derived2 : public Base { /* ... */ };
// ...
Base *arr[10] = {new Derived1(), new Derived1(), new Derived2(), ...};
// ...
for(Base **p = arr; p < arr+10; ++p) {
*p->foo();
// ...
}
If I guessed OP's real problem, I think this would solve it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With