Why is the superclass's default constructor being called?

I am teaching myself the basics of inheritance with the code snippet below.

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
#include <iostream>
using namespace std;

class Polygon {
  protected:
    int x;
    int y;
  public:
    Polygon(int, int);
};

Polygon::Polygon(int x, int y) {
  this->x = x;
  this->y = y;
}

class Square : public Polygon {
  public:
    Square(int);
    int area();
};

Square::Square(int x) {
  Polygon::Polygon(x, x);
}

int Square::area() {
  return this->x * this->y;
}

int main() {
  Square s(5);
  cout << s.area() << endl;
}


As you see, the Square class inherits properties from the Polygon class. However, I am getting the following compilation errors.

1
2
3
4
basicInheritance.cpp: In constructor ‘Square::Square(int)’:
basicInheritance.cpp:24: error: no matching function for call to ‘Polygon::Polygon()’
basicInheritance.cpp:13: note: candidates are: Polygon::Polygon(int, int)
basicInheritance.cpp:5: note:                 Polygon::Polygon(const Polygon&)


Why is the default constructor for Polygon being called? I thought that I had explicitly called a custom constructor for Polygon in the constructor for Square.
Last edited on
In the constructor of a derived class you should call the constructor of the base class in the initialization list, which looks like this:
1
2
3
Square::Square( int x ) : Polygon( x, x ) {
    // constructor body
}


Explanation: http://www.cprogramming.com/tutorial/initialization-lists-c++.html
Last edited on
Topic archived. No new replies allowed.