Jump to content
  • Advertisement
Sign in to follow this  
tendifo

polymorphism in c++

This topic is 4297 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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;
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!