C
ceo
Hi,
Following is a program that doesn't give the expected output, not sure
what's wrong here. I'm adding the size of derived class to the base
class pointer to access the next element in the array. Why does bp
point to some address that is not &d[1]?
Please clarify.
Thanks,
Ceo
#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 << "\n sizeof (base): " << sizeof(base) << endl;
cout << "\n sizeof (derived): " << sizeof(derived) << endl << endl;
cout << " d[0] addr: " << &d[0] << endl;
cout << " d[1] addr: " << &d[1] << endl;
cout << " bp addr: " << bp << endl << endl;
cout << " i = " << bp->get_i() << endl << endl;
bp = bp + sizeof(derived);
cout << " bp addr: " << bp << endl << endl;
cout << " i = " << bp->get_i() << endl << endl;
return 0;
}
output on my machine:
--------------------
sizeof (base): 4
sizeof (derived): 8
d[0] addr: 0012FF6C
d[1] addr: 0012FF74
bp addr: 0012FF6C
i = 1
bp addr: 0012FF8C
i = 3149472
Following is a program that doesn't give the expected output, not sure
what's wrong here. I'm adding the size of derived class to the base
class pointer to access the next element in the array. Why does bp
point to some address that is not &d[1]?
Please clarify.
Thanks,
Ceo
#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 << "\n sizeof (base): " << sizeof(base) << endl;
cout << "\n sizeof (derived): " << sizeof(derived) << endl << endl;
cout << " d[0] addr: " << &d[0] << endl;
cout << " d[1] addr: " << &d[1] << endl;
cout << " bp addr: " << bp << endl << endl;
cout << " i = " << bp->get_i() << endl << endl;
bp = bp + sizeof(derived);
cout << " bp addr: " << bp << endl << endl;
cout << " i = " << bp->get_i() << endl << endl;
return 0;
}
output on my machine:
--------------------
sizeof (base): 4
sizeof (derived): 8
d[0] addr: 0012FF6C
d[1] addr: 0012FF74
bp addr: 0012FF6C
i = 1
bp addr: 0012FF8C
i = 3149472