Inheritance of class

I try to learn inheritance by myself, however, I do not know where is the error in this code.

I try to print:

Rectangle: length = 8 width = 3
24
Square: side = 5
25

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
  #include <iostream>

using namespace std;

class Rectangle
{
private:
    int length;
    int width;
public:
    Rectangle();
    Rectangle(int a, int b);
    int getlength() const;
    int getwidth() const;
    virtual int area();

};


Rectangle::Rectangle()
{
}

Rectangle::Rectangle(int a, int b):length(a), width(b)
{
}

int Rectangle::getlength() const
{
    return length;
}

int Rectangle :: getwidth() const
{
    return width;
}

int Rectangle :: area()
{
    return length * width;
}

ostream& operator<<(ostream& out,const Rectangle& R)
{
    out <<"Rectangle: length = " << R.getlength() << " " << "width = " << R.getwidth();
    return out;
}


class Square : Rectangle
{
private:
    int side;
public:
    Square();
    Square(int a);
    int getside() const;
    int area();
};

Square::Square()
{
}

Square::Square(int a): Rectangle(a,a)
{
}

int Square :: area()
{
    return side * side;
}
int Square::getside() const
{
    return side;
}


ostream& operator<<(ostream& out,const Square& S)
{
    out <<"Square: side = " << S.getside();
    return out;
}


int main()
{
    Rectangle R(8,3);
    cout << R << endl;;
    cout << R.area() << endl;
    Square S(5);
    cout << S << endl;
    cout << S.area() << endl;
}
you just forgot to initialize side.

1
2
3
4
Square::Square(int a): Rectangle(a,a)
{
    side = a;
}
Thank you.
Shouldn't you also be initializing the variables to some default value (e.g. 0) in the default constructors?
Last edited on
Topic archived. No new replies allowed.