2
#include <vector>

class A {
private:
    std::vector<int> v_;
public:
    A(int size = 100, int init_val = 100){
        for(int i=0; i<size; i++)
            v_.push_back(init_val);
    }
};

In the main, if I do:

A a(1000, 100);

What really happens? It is the first time I've seen hardcoded parameters in a constructor!

1
  • I'd suggest to change the title of question to Default values of constructor parameters (and content accordingly). Commented Feb 1, 2013 at 12:20

3 Answers 3

6

The passed values will simply replace default values of parameters with the passed ones.

  • A definition A a; will result in call to A::A(100, 100)
  • A definition A a(5); will result in call to A::A(5, 100)
  • A definition A a(5, 6); will result in call to A::A(5, 6)
Sign up to request clarification or add additional context in comments.

Comments

4

Those aren't "hardcoded", just default parameters. If you don't supply the parameters, then size defaults to 100, and init_val to 100. Parameters that you do supply override the defaults. Hence:

A a1();            // size = 100, init_val = 100
A a2(1000);        // size = 1000, init_val = 100
A a3(1000, 1000);  // size = 1000, init_val = 1000

Comments

1

The declaration

A(int size = 100, int init_val = 100)

does not define "hardcoded parameters", but rather default values. If you call A::A() leaving the parameters away, the compiler will use the default values. That's all there is to it.

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.