-4

  class A{
       public:
           A(){ cout << “A ctor” << endl; }//default A constructor
           A(const A& a){ cout <<“A copy ctor”<< endl; }//copy constructor
           virtual ~A(){ cout <<“A dtor”<< endl; }//destructor
           virtual void foo(){ cout <<”A foo()” << endl; }
           virtual A& operator=(const A& rhs){ cout << “A op=” << endl; }//operator
    };

class B:public A{
   public:
       B(){ cout <<“B ctor”<< endl; }//default B constructor 
       virtual ~B(){ cout <<”B dtor”<< endl; }//destructor
       virtual void foo(){ cout <<”B foo()”<< endl; }
   protected:
       A mInstanceOfA;
}; 

A foo(A& input){
    input.foo();
    return input;
}


Int main(){
    B myB;
    B myOtherB;
    A myA;
    myOtherB=myB;
    myA=foo(myOtherB);
}

This program prints:

A ctor
A ctor
B ctor
A ctor
A ctor
B ctor
A ctor
A op=
A op=
B foo()
A copy ctor
A op=
A dctor

why print 2 times "A ctor" before print "B ctor" and why print at the end of the program "A copy ctor", "A op=", "A dctor"??*/

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
user3746116
  • 67
  • 1
  • 6
  • 1
    What on earth is the blink tag doing in there? On topic, this program doesn't compile, let alone print anything. But it looks like something a [book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) would easily answer. – ghostofstandardspast Jun 16 '14 at 19:52

1 Answers1

1

It prints A twice before B because:

  1. First time is because B derives from A, so its the instantiation of the base class
  2. Second time is because B contains an instance of A as a member variable. So that gets instantiated too, before B's constructor is called.

And at the end, the copy constructor, assignment op, and destructor for A are printed out because foo() is returning an instance of A by value, so it needs to be copied into its destination.

Also, you may want to format and ask your questions a little better or someone will downvote them.

user3690202
  • 3,844
  • 3
  • 22
  • 36