Re: questions about dynamic binding
// bp points to the object b, even if it is a pointer of class A.
A* bp = &b;
// so the member function B::f should be invoked.
bp->f();
// bp2 points to a object of class A.
A* bp2 = new A(*bp);
// so the member function A::f should be invoked.
bp2->f();
about the statement A* bp2 = new A(*bp);
if class A hasn't any copy constructor, the compiler will use the default
copy constructor to construct a new object.
A::A( const A& a),
because class B derives from class A, so the compiler will use A's part of
the object B to construct the object of class A.
if you write a overload copy constructor for class A, such as
A::A( const B& b),
the compiler will use your custom copy constructor to create the object of
class A.
It says "no matching function for call to 'B::B(A&)'". Can't compiler
find out *bp is in fact a B object?
yes, the error is reported at compile time, the dynamic binding is at run
time. so the compiler could not know whether a pointer points to its actual
object at compile time.
"Jess" <wdfcj@hotmail.com>
??????:1178964781.857834.6500@u30g2000hsc.googlegroups.com...
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? If it is the latter, then can I create a B
object by defining my own copy constructor for A?
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?
Thanks,
Jess