#include<iostream>
usingnamespace std;
class Shape {
public:
Shape (int i=0, int j=0) { x = i; y = j; }
double getX() { return x;}
double getY() { return y;}
protected:
double x, y;
};
class Rectangle : public Shape {
public:
Rectangle(int i, int j, int k, int l):Shape(i,j){ x = k; y = l; }
double getX() { return x;}
double getY() { return y;}
double area();
private:
double x,y;
};
double Rectangle::area()
{return (x - Shape::getX()) * (y - Shape::getY());}
int main()
{Rectangle r(0,0,3,5);
cout << "The area of rectangle is: " << r.area();
cin.get();}
We have the same member functions getX() and getY() in both class Shape and Rectangle. In order to call the member functions from the parent class, we use the Shape::getX() and Shape::getY().
The formula thus is (3-0)*(5-0) in line 24.
But when I try to further test this program, changing the parameters in line 6, the variable of i and j, it stills gives me the same answer(15).
Is that the first two parameter in object r, line 27,permanently override the values assigned in line 6?
0 and 0 [line 27] are passed as i and j to the Rectangle constructor on line 15, which in turns calls the Shape constructor with i and j. The Shape constructor on line 6 fills out x and y with the 2 values passed to it. In your case, 0 and 0.
There is no "overriding" going on. Shape just copies the values that were passed to its constructor. If no parameters are passed, it uses 0 and 0.