Re: questions about dynamic binding
On 2007-05-12 12:13, Jess wrote:
Hello,
I have some questions to do with dynamic binding. The example program
is:
#include<iostream>
using namespace std;
class A{
public:
virtual void f(){cout << "A::f()" << endl;}
};
class B:public A{
public:
void f(){cout << "B::f()" << endl;}
};
int main(){
B b;
A* bp = &b;
// A* bp2 = new B(*bp);
A* bp2 = new A(*bp);
bp2->f();
bp->f();
return 0;
}
As I expected "bp->f()" calls B's f(). However, "bp2->f()" calls A's
f(). Is it because of the "new A", which only copies the A's part of
"*bp" object, or is it because of the behaviour of the synthesized
copy constructor of A?
It's because new A() will create a new object of type A, so when doing
bp2->f() it will call the f() method of the object pointed to by bp2
(which happens to be of type A). When you do bp->f() the type of the
object pointed to is of type B so its f() is called.
If it is the latter, then can I create a B object by defining my own
copy constructor for A?
No, any constructor in an object (regardless if it's a normal
constructor or a copy-constructor) of type T will create an object of
type T, so when you do 'new A()' the type of the object will always be A
(since that is what you specified).
In addition, the statement that is commented out produced compiler
error. It says "no matching function for call to 'B::B(A&)'". Can't
compiler find out *bp is in fact a B object?
No, bp is a pointer to an object of type A, you can either cast the
pointer to a pointer of type B or create a constructor in B which takes
an A as argument.
--
Erik Wikstr?m