Program Out Put Does Not Make Sense!

I try to test what the output of this program would be, but it doesn't make any sense,

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <iostream>

using namespace std;



//Why the op= is invoked twice

class A {



public:

        A()

        {

            cout<<"A ctor"<<endl;

        }

        A(const A &a)

        {

            cout <<"A copy ctor"<<endl;

        }

        ~A()

        {

            cout<<"A dtor"<<endl;

        }

        virtual void foo()

        {

            cout<<"A foo()"<<endl;

        }

        virtual A& operator=(const A &rhs)

        {

            cout<<"A op="<<endl;

        }

};



class B:public A

{

    public:

            B():A()

            {

                cout<<"B ctor"<<endl;

            }

            ~B()

            {

                cout<<"B dtor"<<endl;

            }

            virtual void foo()

            {

                cout <<"B foo()"<<endl;

            }

            protected:

            A myIstanceOfA;



};







A foo (A &input)

{

    input.foo();

    return input;

}





int main()

{

    B myB;

    B myOtherB;

    A myA;

    myOtherB=myB;

    myA=foo(myOtherB);

}







A ctor

A ctor

B ctor

A ctor

A ctor

B ctor

A ctor

A op=

A op= // WHY IS OP= EVOKED TWICE, IT SHOULD BE ONLY ONCE.

B foo()

A copy ctor

A op=

A dtor

A dtor

B dtor

A dtor

A dtor

B dtor

A dtor

A dtor


The op= or overloaded operator equal is evoked twice, where it should have only be once, any idea on what went wrong.
I remember seeing a program like this, but I think what's happening is that you're inheriting class A in your class B, so when you do it for class B it's gonna see everything that is pubilc in A, which in this case is everything. So it's inheriting the op part, which might cause it to print twice...

Note:
this is just a guess, so don't quote me on this, lol. I most likely am off in my reasoning.
Your B class inherits from your A class, which means in calls A's =. Since you also didn't define an = for B, the compiler will make one for you, which means it also calls the = on the A member in your B class.
ah, so the default op= in B will call op= in A, am i correct?
actually its incorrect, the op= is envoked twice, for one = since there is a base class member in the derived class(the protected one)
Topic archived. No new replies allowed.