0

I am attempting to add a copy constructor to each in order to run the main function. What I have implemented right now currenrtly prints out "b2.valuea = -858993460 b2.valueb = 10" So it reads valueb correctly but obviously something is going wrong with valuea. Advice?

#include "stdafx.h" #include <iostream> using namespace std; class A { int valuea; public: int getValuea() const { return valuea; } void setValuea(int x) { valuea = x; } // copy constructor A() {} A(const A& original) { valuea = original.valuea; } }; class B : public A { int valueb; public: int getValueb() const { return valueb; } void setValueb(int x) { valueb = x; } // copy constructor B(){} B(const B& original) { valueb = original.valueb; } }; int main() { B b1; b1.setValuea(5); b1.setValueb(10); B b2(b1); cout << "b2.valuea = " << b2.getValuea() << "b2.valueb = " << b2.getValueb() << endl; } 

1 Answer 1

1

You are not calling the copy constructor of your base-class in your derived copy constructor. Change it like:

B(const B& original) : A(original){ valueb = original.valueb; } 

And it will output

b2.valuea = 5 b2.valueb = 10 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.