12

Right now I have a class A that inherits from class B, and B does not have a default constructor. I am trying the create a constructor for A that has the exact same parameters for B's constructor

struct B {
  int n;
  B(int i) : n(i) {}
};

struct A : B {
  A(int i) {
    // ...
  }
}; 

but I get:

error: no matching function for call to ‘B::B()’
note: candidates are: B::B(int)

How would I fix this error?

3
  • 1
    Please post your current code Commented Sep 15, 2010 at 1:59
  • @Ramon Zarazua--why? I've already gotten the answer... Commented Sep 16, 2010 at 18:04
  • 3
    @wrongusername Because Stackoverflow is a collective and aims to help more people than just the asker. People with the same problem will search for this question and use the answers for a solution to their problem. But in order to do that they need to know that their problem is the same as yours. By providing code that exhibits your problem, other people can much easier and quicker determine whether the question (and ultimately the answers) apply to them. Commented Aug 20, 2018 at 13:44

2 Answers 2

23

The constructor should look like this:

A(int i) : B(i) {}

The bit after the colon means, "initialize the B base class sub object of this object using its int constructor, with the value i".

I guess that you didn't provide an initializer for B, and hence by default the compiler attempts to initialize it with the non-existent no-args constructor.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for explaining what that means, Steve! I didn't realize there was an initializer
9

You need to invoke the base constructor via your class' initializer list.

Example:

class C : public B
{
public:
    C(int x) : B(x)
    {
    }

};

When you don't initialize B explicitly it will try to use the default constructor which has no parameters.

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.