0

my code:

#include "BaseProduct.h"

BaseProduct::BaseProduct(
    const ProductBaseType baseType,
    const int id,
    const int quantity,
    const Location location
    ) {
    _baseType = baseType;
    _id = id;
    _quantity = quantity;
    _location = location;
}

Error I'm getting:

no default constructor exists for class "Location"

I know there isn't any default constructor for Location, it's intended... I'm using VSCode if it's of any relevance.

Thanks in advance!

  • 1
    Try using the initialization list of the `BaseProject` constructor, instead of using the body. Also, if you're passing in objects, you should pass in by constant reference. – ChrisMM Dec 02 '19 at 11:26
  • What do you mean by that? Can you show an example? – Yuval Saraf Dec 02 '19 at 11:27
  • Check out the [list of recommended books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Dec 02 '19 at 11:33
  • 3
    Having the function arguments be `const` is an anti-pattern; you probably want to move them into the class members instead (otherwise you have a bunch of unnecessary copy operations) – M.M Dec 02 '19 at 11:42

2 Answers2

2

You might want to rewrite the constructor to use the initializer list form. Otherwise the default constructor will be used for your members before you can initialize them in the constructor body:

Quote from above linked documentation (emphasis mine):

Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished. Member initializer list is the place where non-default initialization of these objects can be specified. For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.

Example:

BaseProduct::BaseProduct(
    const ProductBaseType baseType,
    const int id,
    const int quantity,
    const Location location
    ) : _baseType(baseType), _id(id), _quantity(quantity), _location(location) { }
moooeeeep
  • 31,622
  • 22
  • 98
  • 187
1

Use the member initializer list:

BaseProduct::BaseProduct(
    const ProductBaseType baseType,
    const int id,
    const int quantity,
    const Location location
  ) : // the colon marks the start of the member initializer list
    _baseType(baseType),
    _id(id),
    _quantity(quantity),
    _location(location)
  {
      // body of ctor can now be empty
  }
}

This lets you use composition of objects that are not default constructible.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108