J
Jess
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 Bublic 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
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 Bublic 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