I have an interesting problem to deal with. Is there any way to call derived class functions with base class pointer without virtual pointers? IMHO, I do not think so but would like to clear with experts.
Consider this example:
class B {
public:
int a;
int b;
int get_a() { return a };
int get_b() { return b };
B() : a(1), b(2) { }
};
class D : public B {
public:
int a;
int b;
int get_a() { return a };
int get_b() { return b };
D() : a(3), b(4) { }
};
int main() {
Base* b = new Base;
std::cout << b->get_a() << std::endl; // Gives 1
std::cout << b->get_b() << std::endl; // Gives 2
// Do something here which instantiates Derived and can call Derived functions using base class pointers.
// Maybe Base\* b = new Derived();
// But doing b->get_a() should call Derived class function get_a.
std::cout << <some_base_class_pointer_after_doing_something>->get_a() << std::endl; // Should give 3
std::cout << <some_base_class_pointer_after_doing_something>->get_b() << std::endl; // Should give 4
}
Is there any possible way? reinterpret_cast or anything else?
I do not want to use virtual since vptr comes into the picture and increases the memory by 8 bytes(depends) per object. Very frequently, I can have big number of B type objects. Say, 1 million objects of B type, I do not want my program memory to go by 1m x 8 bytes. Instead, I would rather not have virutal/vptr in such huge cases.
I would be happy to write more details if needed.