PDA

View Full Version : C++ view data on derived type from base pointer



dgbaur
01-05-2011, 01:24 PM
class A {
public:
virtual ~A()
{};

virtual dump(std::ostream &os) const = 0;
}

class B : public A {

B():
value(1)
{}

virtual dump(std::ostream &os) const {
os << value;
}

private:
int value;
}

main() {
...
A * a = new B;

a.dump(cout);
...
}


When I dive on a, the data for a is solely the int(...)** virtual table pointer, but i knows that the type is B. Yet the window does not show the type as B, rather it displays it at A, therefore I do not see 'value'. Is there a way to get totalview to display the derived type information knowing the type via the virtual table pointer? Or do I have to change the type myself?

PeterT-RogueWave
10-20-2014, 02:43 PM
Well, this one has been sitting around for a while without an answer but it has gotten a lot of views and I was asked about this today with reference to this post, so I'll put in my two cents. The debugger is only going to know as much as the compiler tells it. Given this bit of code, the variable 'a' is defined as Class A, even though we use the constructor for Class B. So, when you dive on it, the fact you see only Class A is due to the fact that the debug information for this variable declares it as Class A. Since we are using the constructor for B, you can change the type from Class A * to Class B * and then dive on the pointer to get to the entry for 'value'.

Cheers,

StephaneR-Coventor
01-16-2015, 06:46 AM
Actually, thanks to the virtual table and with the same information from the compiler, GDB can actually recover the complete type of 'a' (Using "set print object on"):
(gdb) set print object on
(gdb) p a
$2 = (B *) 0x6020d0

Here the type of 'a' is obvious, but this is often not the case. Is there a way to lobby for this feature?