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!

4
  • 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. Commented Dec 2, 2019 at 11:26
  • What do you mean by that? Can you show an example? Commented Dec 2, 2019 at 11:27
  • Check out the list of recommended books. Commented Dec 2, 2019 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) Commented Dec 2, 2019 at 11:42

2 Answers 2

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) { }
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.