polymorphism in c++

Started by
0 comments, last by morx 17 years, 1 month ago
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;
}

Advertisement
You are correct; the default copy constructor provides a simple copy of all data members from 'g' to 'h' which causes both 112 and 234 to appear in the new object.

This topic is closed to new replies.

Advertisement