2

I am trying to compile a code that involves inheritance.

#include "MapEntityClass.h"

class RectangularEntityClass:public MapEntityClass
{
  public:
    void drawOnMap(MapClass *mapObj) const;

  protected:
};

The parent class is MapEntityClass, which does not have a default constructor, but has a value constructor. When I compile, I get the following error:

RectangularEntityClass.h: In constructor ‘RectangularEntityClass::RectangularEntityClass()’:
RectangularEntityClass.h:12:7: error: no matching function for call to ‘MapEntityClass::MapEntityClass()’
   class RectangularEntityClass:public MapEntityClass
   ^
RectangularEntityClass.h:12:7: note: candidates are:
In file included from main.cpp:1:0:
MapEntityClass.h:32:5: note: MapEntityClass::MapEntityClass(const PixelLocationClass&, const ColorClass&)
     MapEntityClass(
     ^
MapEntityClass.h:32:5: note:   candidate expects 2 arguments, 0 provided

Any idea what is wrong?

hgiesel
  • 5,430
  • 2
  • 29
  • 56
roulette01
  • 1,984
  • 2
  • 13
  • 26
  • 2
    As the class is right now, the compiler creates the RectangularEntityClass's default constructor. In that implementation, it tries to call the default constructor of its parent class (default behavior). You might want to define RectangularEntityClass's default constructor yourself in order to call MapEntityClass's value constructor with the appropriate values – Bettorun Apr 17 '16 at 02:28
  • hmm, you mean the default constructor of rectangularEntityClass? – roulette01 Apr 17 '16 at 02:29
  • yeah. In order to specify which constructor to use for MapEntityClass – Bettorun Apr 17 '16 at 02:30

1 Answers1

3

In inheritance, the subclass need not have a constructor only if parent class doesn't have a constructor or only default constructor.

In any case, if parent class happens to have a parameterized constructor, the subclass should have a parameterized constructor which should invoke the parent class constructor.

Example:

class A {
    int aVal;
    public:
        A(int);
};

A::A(int aVal)
{
    this->aVal = aVal;
}

class B : public A {
    int bVal;
    public:
        B(int, int)
};

B::B(int aVal, int bVal) : A(aVal)
{
    this->bVal = bVal;
}
aliasm2k
  • 883
  • 6
  • 12