0

I created a class with a constructor that takes an int to determine the size of a linked list the object has. The problem I'm having is I need to be able to call this constructor when this object is instantiated as a private member of another class. So basically:

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

class B {
    const int size = // any number > 0
private:
    A a(size);
};

I get this error:

constant "B::size" is not a type name

I've tried searching online, but I can't come across this specific issue. It could be that I'm struggling to word the question correctly... it's a weird issue I haven't seen yet. Any help is appreciated!

5
  • You have declared methods but you have not implemented them. Where's the implementation? Commented May 11, 2014 at 8:46
  • That's a faulty design. I suggest you ask about the actual problem you are trying to solve, and not about the solution you had in mind. Commented May 11, 2014 at 8:47
  • The constructor for A should be called in the constructor for B. You can't instantiate directly in a header file unless you are using a constant. Commented May 11, 2014 at 8:48
  • Your declaration of A a(size); is wrong, should be A a; and initialize the a member in class B's constructor member initialization list. Commented May 11, 2014 at 8:48
  • Thanks donutmonger and πάντα ῥεῖ! Commented May 11, 2014 at 8:59

2 Answers 2

3

You cannot call the constructor with parameters in the member variable declaration.

You can implement a constructor for B and do it there.

B::B() : a(size) {}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That's exactly what I was looking for. I have no idea why I didn't try that...
2

You have to do in the B constructor, using an initializer list:

class B
{
public:
    B() : a(size)
    {}

private:
    A a;
    const int size = ...;
};

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.