Is there a default constructor with no variable that needs to redefine the child classes in C ++?

2

When compiling a program, I have a curious error:

MaxSize.cpp: In constructor ‘MaxSize::MaxSize(int)’:
MaxSize.cpp:7:26: error: no matching function for call to ‘TasMin::TasMin()’
 MaxSize::MaxSize(int size){
In file included from MaxSize.h:1:0,
                 from MaxSize.cpp:3:

I thought it was because a redefinition of a constructor in MaxSize.h is missing that inherits from TasMin but does not have TasMin.h a constructor TasMin() , only TasMin(int size) :

class TasMin
{
  public:
    TasMin(int size);
    // eso es...
    
asked by ThePassenger 25.04.2017 в 17:59
source

2 answers

3

C ++, by default, tends to create a base implementation of certain basic functions, which are:

  • Default constructor
  • Copy constructor
  • Constructor move (C ++ 11)
  • Destroyer
  • Assignment operator
  • Assignment operator move (C ++ 11)

The problem arises when specific functions are provided. In this case, the compiler stops implementing certain functions.

On the other hand, when you inherit a class the base class always has to call some constructor of the parent class. If no constructor is specified, the one that ends up being called is the default constructor as seen in the following example:

struct Base
{
  Base()
  { std::cout << "Base::Base()\n"; }
}

struct Derivada : Base
{
  Derivada()
  { std::cout << "Derivada::Derivada()\n"; }
}

int main()
{
  Derivada d;
}

Exit:

Base::Base()
Derivada::Derivada()

In your case, when implementing a specific constructor, the compiler leaves aside the implicit implementation of the default constructor. The solution is to implement it explicitly or call a different base constructor:

Explicit implementation

class TasMin
{
  public:
    TasMin(){ } // Constructor por defecto explicito
    TasMin() = default; // Constructor por defecto (C++11)
    TasMin(int size);
};

Call an explicit base constructor:

MaxSize::MaxSize(int size)
 : TasMin(size)
{ }
    
answered by 25.04.2017 / 18:16
source
1

When you create an instance of a subclass, what you do it's :

  • The necessary memory is reserved.

  • The constructor of your derived class is called.

  • The appropriate constructor of the parent class is called .

  • The initialization list is processed.

  • Your constructor is running.

  • The object is returned.

And what is the appropriate constructor of the parent class? If you only have one parent class and one default constructor (without parameters), then that one. If not, you will have to specify the constructor to which it is called; for example

class MaxSize: public TasMin
{
   public:

      MaxSize(int size) : TasMin(size) {
         ...
      }
   ...
 }
    
answered by 25.04.2017 в 18:15