简体   繁体   中英

Is it possible to create a pointer to an inherited class by incrementing a base class pointer(C++)?

Based on what I've read, it seems the memory for derived objects is made sequentially with the base class and all its data made first and then immediately followed by the following classes down the inheritance tree. So if I make a base class pointer that is equal to a new derived class object, and then increment it by one(which will actually add the size of the base class to the address), then will I arrive at the derived class? If so, can I then access the derived class's data in this way?

Yes, and no. In the very simplest case it will work in most cases:

class Base {
public:
int v;
};

class Derived : public Base {
public:
   int b;
};

int main() {
   Derived d;
   Base* p = &d;
   p++;

   // these will match on all compilers I'm aware of
   printf("%p %p\n", p, &d.b);
   return 0;
}

For single inheritance, that is typically what you'll see from most compilers (although I'd be very worried actually relying on that in production code!)

However, sadly things aren't always that simple! In C++ we often have multiple inheritance, virtual inheritance, abstract base classes and all those bits of goodness. So here is a scenario where it would absolutely not work!

struct Animal {
    virtual ~Animal() = default;
    virtual void Eat() {}
    int a;

};

struct Mammal: Animal {
    virtual void Breathe() {}
    int b;
};

struct WingedAnimal: Animal {
    virtual void Flap() {}
    int c;
};

// A bat is a winged mammal
struct Bat: Mammal, WingedAnimal {
    int d;
};

There are however far safer approaches to handling upcasting (eg dynamic_cast, or your own RTTI system). You probably will want to be using those :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM