I'm a brand new in C++ and I'm experimenting with Polymorphism. I have the following code:
#include <iostream>
class Base1
{
protected:
int b1;
public:
int m() { return 1; }
};
class Base2
{
protected:
int b2;
public:
int n() { return 2; }
};
class Der : public Base1, public Base2
{
protected:
int d1;
public:
int m() { return 11; }
int n() { return 21; }
};
int main()
{
Der *ptr = new Der();
Base1 *b1 = ptr;
Base2 *b2 = ptr;
std::cout << "d: " << ptr << ", m: " << ptr->m() << ", n: " << ptr->n() << "\n";
std::cout << "b1: " << b1 << ", m: " << b1->m() << "\n";
std::cout << "b2: " << b2 << ", n: " << b2->n() << "\n";
delete ptr;
return 0;
}
When i run this code the interesting thing is that b2 is shifted by 4 bytes, here my output:
d: 0x564eab6cbeb0, m: 11, n: 21
b1: 0x564eab6cbeb0, m: 1
b2: 0x564eab6cbeb4, n: 2
Why this happens only with b2? I guess it's related on how things are stored in memory because if I remove the int field in b1 b2 is not affected. Is there a way to see easily stack and heap? I would like to see what happens. (I'm using Virtual Studio Code)