Kench wrote:
> Sorry if this becomes a repost. I posted this to comp.lang.c++.moderated 1
> hour ago still it does not show up there so posting this here.
It takes moderators up to a day to get through all posts in a moderated
newsgroup, usually. You should not expect a chat room performance from
the Usenet.
> Consider class A & B both of which implement a copy constructor.
> class B inherits from A.
> When copy constructor of B is called, first the constructor of A gets called
Not unless you specifically omit initialising the base class object.
> My question is that, why the copy constructor for A not called.
You didn't initialise the base class. It calls the default c-tor.
> Is there a way to have it call the copy constructor of class A?
Of course. See below.
>
> #include <iostream>
> using namespace std;
>
>
> class A
> {
> public:
> A() { cout << "A constructor called\n";};
First of all, lose all the semicolons after function bodies. It
just looks so amateurish and sloppy...
> A(A& a) { cout << "Copy A constructor called\n";};
> ~A() { cout << "Destructor A called\n";};
> };
> class B: public A
> {
> public:
> B() { cout << "B constructor called\n";};
> B(B& b) { cout << "Copy B constructor called\n"; };
You need to say
B(B& b) : A(b) { ...
to make sure that the 'A' part is copy-constructed.
> ~B() { cout << "Destructor B called\n";};
> };
> int main(void)
> {
> B b;
> B bb = B(b);
> return 0;
> }
Victor
|