67 108
Assignments Done
99,3%
Successfully Done
In November 2018

Answer to Question #22172 in C++ for Ahmed

Question #22172
o Inheritance code in C++
Expert's answer
#include <iostream>

using namespace std;

class Shape
{
private:
char unused;

protected:
int x, y;

public:
string name;

void SetPosition(int x, int y)
{
this->x = x;
this->y = y;
}
};

/* Using 'protected' inheritance specifier.
Public and protected members of the parent class become protected.
Private members stay private */
class Rectangle : protected Shape
{
public:
void SetName(string name)
{
/* The child class has access
to the public fields of the parent class */
this->name = name;
}

void Move(int delta_x, int delta_y)
{
/* We have also access to the protected fields of the parent class */
this->x += delta_x;
this->y += delta_y;

//this->unused = '$'; //this is wrong
}
};

void main()
{
Rectangle rect;
rect.SetName("rect_1");

/* The line below causes compilation error
because SetPosition is a protected method */
//rect.SetPosition(2, 4);
rect.Move(8, -3);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions