|
-
January 12th, 2010, 05:31 PM
#1
Explain the Output
This is a dumb question, going back to the basics, but I want to understand the "why" of it, so I'm posting it anyway.
Given the following code:
Code:
#include <iostream>
using namespace std;
class A
{
public:
virtual void print() { cout<< "A.Print\n"; }
A() { cout <<"Constructor of A.\n"; }
};
class B : public A
{
public:
void print() { cout << "B.print\n"; }
B() { cout <<"Constructor of B.\n"; }
};
int _tmain(int argc, _TCHAR* argv[])
{
B *b = new B(); // ??
reinterpret_cast<A *>(b)->print();
return 0;
}
The output of which is:
Constructor of A.
Constructor of B.
B.print
My question is: How? How does the base-class know to call the derived class' print method? My mind is saying that the logic is "we've cast to class A" and class A knows nothing of class B, and yet the print method in class B is still being called.
Is it going to the virtual function table even though we're class A? That's the only thing I can conclude.
-
January 12th, 2010, 05:50 PM
#2
Re: Explain the Output
Yes it is. By declaring the print function virtual in 'A', when you create a 'B' the compiler knows that it should call 'B's print no matter what you cast the pointer to.
In the context of v-tables, when the compiler defines an A, it puts the address for A:: print in it. Then, when it defines 'B', it overwrites the address of A:: print with B:: print in B's definition.
Viggy
-
January 14th, 2010, 03:30 PM
#3
Re: Explain the Output
Is it going to the virtual function table even though we're class A? That's the only thing I can conclude.
Yes, that is the whole point of a virtual function. You need to read about dynamic run-time binding and design patterns such as the bridge abstract factory patterns for starters. It is really important to know why this behavior exists so that you can understand some basic design patterns. This is really critical for any C++ developer to know. There are many times where you want to hide dependencies on implementation classes in order to separate interface from implementation so that they can vary independently.
Last edited by kempofighter; January 14th, 2010 at 03:31 PM.
Reason: added quote tags
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|