views:

91

answers:

2

I have this code:

#include <stdio.h>

class A
{
public:
    A() { printf("A::A()\n"); }
    A(const A &a) { printf("A::A(A &a)\n"); }
    A &operator=(const A &a) { printf("A::operator=\n"); }
};

class B : public A
{
public:
    B() { printf("B:B()\n"); }
    B(const A &a) : A(a) { printf("B::B(A &a)\n"); }
    B &operator=(const B &b) { printf("B::operator=\n"); }
};

int
main(int argc, char *argv[])
{
    printf(">> B b1\n");
    B b1;
    printf(">> b2 = b1\n");
    B b2 = b1;
    return 0;
}

Why the line B b2 = b1 does not call the constructor B::B(const A &a) and instead calls A::A(const A &a)? How can I tell the compiler to do so?

+5  A: 

Because it calls B::B(const B &a) which in turn calls A::A(const A &a). And you missed B::B(const B &a) in your class so you can't see it.

Tomek
That's it, thank you!
Leandro
A: 

That is because:

This:

B(const A &a)  
{ 
    printf("B::B(A &a)\n"); 
}

is not a copy constructor!

However, this:

B(const B &a)  
{ 
    printf("B::B(A &a)\n"); 
}

is a copy constructor.

With your version of copy constructor, you are ruining stack as well.

To prove you my point about stack corruption, you have got to try this:

Notice that it will never print "Inside B::Print()"

class A
{
public:
    A() { printf("A::A()\n"); }
    A(const A &a) 
    { 
        printf("A::A(A &a)\n"); 
    }
    A &operator=(const A &a) { printf("A::operator=\n"); }
    void print(){printf("Inside A::Print()\n"); }
};

class B : public A
{
public:
    B() { printf("B:B()\n"); }
    B(const A &a)  
    { 
        printf("B::B(A &a)\n"); 
    }
    B &operator=(const B &b) { printf("B::operator=\n"); }

    void print(){printf("Inside B::Print()\n");}
};

int main(int argc, char *argv[])
{
    printf(">> B b1\n");
    B b1;
    b1.print();
    printf(">> b2 = b1\n");
    B b2 = b1;
    b2.print();
    return 0;
}
bits
bits
Leandro
Yeah you are right. I guess I must have been wrong about the stack corruption. I said that earlier because I was in the debugging mode, and probably because of how implicitly A's copy constructor is called, my debugging would stop at that point.Later I ran it without debugging it and it printed both print() funcs.
bits