Confusion on Virtual function,copy constructor,and type conversion

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Visame
    New Member
    • Dec 2007
    • 7

    Confusion on Virtual function,copy constructor,and type conversion

    Code:
    #include <iostream>
    using namespace std;
    
    class   A
    {
    public:
        A() {cout << "constructor A" << endl;}
        A(A& a) {cout<<"copy A"<<endl;}
        virtual   void   Test(){cout <<"A   test" <<endl;}
    };
    
    class   B:public   A
    {
    public:
        B() {cout << "constructor B" << endl;}
        B(B& b) {cout<<"copy B"<<endl;}
        void   func(){Test();}
        virtual   void   Test(){cout <<"B   test" <<endl;}
    };
    
    
    class   C:public   B
    {
    public:
        C() {cout << "constructor C" << endl;}
        C(C& c) {cout<<"copy C"<<endl;}
        virtual void   Test(){cout <<"C   test" <<endl;}
    };
    
    
    void   main()
    {
        C   c;
        ((B*)(&c))-> func();
        ((B)c).func();
        cout.flush();
    
        int i;
        cin >> i;
    }
    
    //output is here:
    
    constructor A
    constructor B
    constructor C
    C   test
    constructor A//Here is my question
    copy B
    B   test
    I can't understand the above output, especially the latter part:
    ((B)c).func(); gives out the following results:
    constructor A//Here is my question
    copy B
    B test

    Please help me.Thanks!
  • RRick
    Recognized Expert Contributor
    • Feb 2007
    • 463

    #2
    The problem is in line 35.
    Code:
    ((B)c).func();
    You are telling the compiler to construct an object B from c. This will cause the compiler to make a copy of c using B's copy constructor which will first call the A constructor.

    If you want a dynamic cast from C to B without the construction of a new object, you need to convert the pointer (or possibly the reference) to c. The code looks like
    Code:
    ((B*)(&c))->func();
    .

    Comment

    Working...