Given the following segments of code, add the following: A default constructor f
ID: 3810888 • Letter: G
Question
Given the following segments of code, add the following: A default constructor for Class A o Class B A copy constructor for: o Class A Class B Write a main function to test class B o Show that class B inherits functions from class A o Also, show that class B has functions of its own CLASS A class A int getValuca0 const retum valuca: void setvaluea(int x) valaca ladd a default constructor Madd a copy constructor CLASS B class B: public A public: int getValuebo const return valueb: 1 void set Valueb (int x) valueb x; ladd a default constructor lladd a copy constructor private:
Explanation / Answer
PROGRAM CODE:
#include <iostream>
using namespace std;
class A
{
public:
//default constructor for initializing values
A(){valuea = 0;}
//copy constructor - copies the values of other object
A(A &other){valuea = other.getValuea();}
int getValuea() const{return valuea;}
void setValuea(int x){valuea = x;}
private:
int valuea;
};
class B : public A
{
public:
//default constructor for initializing values
B(){valueb = 0;}
//copy constructor - copies the values of other object
B(B &other):A(other)
{valueb = other.getValueb();}
int getValueb() const{return valueb;}
void setValueb(int x){valueb = x;}
private:
int valueb;
};
int main(void) {
B b;
b.setValueb(5);
b.setValuea(10);
B b1(b);
//prints the value of b
cout<<"Value of b: "<<b1.getValueb()<<endl;
//prints the value of a - this is posssible because of inheritance
cout<<"Value of a: "<<b1.getValuea()<<endl;
return 0;
}
OUTPUT:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.