1

How to initialize parameterised constructor as default constructor in c++? This question was asked in my exam. We were given a parametrized constructor & it worked as default constructor too.

0

3 Answers 3

5

A default constructor, per standard (12.1/4), is:

A default constructor for a class X is a constructor of class X that can be called without an argument

So you just need to give the arguments default values:

class Foo
{
public:
    Foo(int a = 6)
    {

    }
};

int main()
{
    Foo obj;
}
Sign up to request clarification or add additional context in comments.

Comments

1
class A
{
    A(int a = 0)
    {
        std::cout << a;
    }
};

Just predefine the parameters with default values.

Comments

0

When a constructor can be invoked with no arguments, it is called a default constructor.

However, a constructor that takes arguments can be turned into a default constructor when its arguments are given default values.

For example:

class String {
public:
    String(const char∗ p = ""); // default constructor : empty string
    // ...
}

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.