Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

class A { int w; public: A(int w = 0) { setW(w); } void setW(int w){ this->w = w

ID: 3710743 • Letter: C

Question

class A
{
int w;

public:
A(int w = 0)
{
setW(w);
}

void setW(int w){
this->w = w;
}

int getW(){ return w; }

double manipulate();
};

class B : public A
{
int x;

B(int w, int x) : A(w){
setX(x);
}

void setX(int x){ this->x = x; }

int getX() {return x; }

double manipulate() { return (getW() * x) / 3.0; }

};

class C : public A
{
int y;

C(int w , int y) : A(w){ setY(y); }

void setY(int y){ this-> y = y; }

int getY() { return y; }

double manipulate { return getW / 5.7; }

};

int main()
{
A **group = new A*[4];

//To be completed

}

The preceding code is an attempt at inheritance and polymorphism. I think I have the inheritance part down but polymorphism is posing a big problem. I know that there is a function in class A that needs some adjusting in order to make the class a pure virtual base class. So, for a grade, I need help adjusting class A to a pure virtual base class. That way, I can also get away with not defining a function body for a particular function in A that is overridden in B and C.

Also, I got stuck in main. I think I am on track to create an array of type A. Since it was my hope that A be a pure virtual base class (thus abstract), I want create an array of type Bs and Cs. Can you help me to dynamically allocate two objects of type B and two objects of type C and place them in the declared array? Then, in a loop print out the values that the manipulate function calculates. Then, be sure to release the memory that was dynamically allocated.

Explanation / Answer

#include <iostream>

using namespace std;

class A
{
int w;

public:
A(int w = 0)
{
setW(w);
}
  
void setW(int w){
this->w = w;
}
  
int getW(){
return w;
}
  
// pure virtual function
virtual double manipulate() = 0;
};

class B : public A
{
int x;

public:
B(int w, int x) : A(w){
setX(x);
}
  
void setX(int x){
this->x = x;
}
  
int getX() {
return x;
}
  
double manipulate() {
return (getW() * x) / 3.0;
}
};

class C : public A
{
int y;

public:
C(int w , int y) : A(w){ setY(y); }
  
void setY(int y){
this-> y = y;
}

int getY() {
return y;
}

double manipulate() {
return (getW() / 5.7);
}
};

int main()
{
A **group = new A*[4];
group[0] = new B(2, 3);
group[1] = new B(3, 5);
group[2] = new C(4,8);
group[3] = new C(8,4);

for(int i = 0; i < 4; i++) {
cout << group[i]->manipulate() << endl;
}
delete [] group;

}

Sample run