I'm a little confused about how polymorphism works in C++.
My test code is below (it was quickly coded up).
When I run the code below, I get the output I expect. I get:
B=
A=
Acopy
Bcopy
112, 234
Press any key to continue . . .
However, when I comment out the B's copy constructor and operator= methods, I get some not-so-expected output:
A=
Acopy
112, 234
Press any key to continue . . .
I get why only A= and Acopy are printed, but why is the number 234 copied as well.. I never defined that operation. The only reasoning is that the default copy constructor is invoked for all the B's elements. Is this correct?
Thanks.
#include <iostream>
using namespace std;
class A
{
public:
int a;
A() { a = 0; }
A(const A& other) {
cout << "Acopy" << endl;;
a = other.a; }
A& operator=(const A& other) {
cout << "A=" << endl;;
a = other.a; return (*this); }
};
class B : public A
{
public:
int b;
B() : A() { b = 0; }
B(const B& other) : A(other) {
cout << "Bcopy" << endl;
b = other.b; }
B& operator=(const B& other) {
cout << "B=" << endl;
A::operator=(other); b = other.b; return (*this); }
};
int main()
{
A f;
B g;
B h;
g.a = 112;
g.b = 234;
h = g;
B i = g;
cout << h.a << ", " << h.b << endl;
system("pause");
return 0;
}