Sign in to follow this  

polymorphism in c++

This topic is 3934 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
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

This topic is 3934 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this