1

I have written a test program:

#include <iostream>

class base
{
        public:

        base()
        {
                std::cout << "base 1" << std::endl;
        }

        base(int a)
        {
                std::cout << "base a=" << a << std::endl;
        }
};

class child : public base
{
        public:

        child()
        {
                std::cout << "child" << std::endl;
        }
};

int main(int argc, char* argv[])
{

        child c;

        return 0;
}

The program outputs the following:

$ ./a.out

base 1
child

Is there any possible way to send an integer argument to the base class thus calling the other form of the base constructor?

In the case that base has only one constructor I get a compile error: candidate expects 1 argument, 0 provided, as you might expect. But if I give a default argument to that constructor, like:

base(int a = 10)

then my program compiles and runs, with the output: base a=10. (Interesting?)

Is there any way to pass in a variable value of a?

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225

2 Answers2

5

You may call the base constructor in the mem-initializer list of the constructor of the derived class

    child() : base( 10 )
    {
            std::cout << "child" << std::endl;
    }

The other way is to place using declaration in the derived class

class child : public base
{
        public:

        using base::base;

        child()
        {
                std::cout << "child" << std::endl;
        }
};

In this case the derived class will have also a constructor with a parameter that will call the corresponding constructor with a parameter of the base class.

Here is a demonstrative program

#include <iostream>

int main()
{
    class base
    {
        public:

        base()
        {
                std::cout << "base 1" << std::endl;
        }

        base(int a)
        {
                std::cout << "base a=" << a << std::endl;
        }
    };

    class child : public base
    {
        public:

        using base::base;

        child()
        {
                std::cout << "child" << std::endl;
        }
    };

    child c( 10 );
}            

The program output is

base a=10
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

You can use the : syntax to call a non-default constructor:

child() : base(1)
Mureinik
  • 297,002
  • 52
  • 306
  • 350