Invoking overload constructor within constructor

65 views Asked by At

I was wondering either it is possible in c++ to run a constructor overload within another constructor. I know it is possible using regular methods. What I am tryng to do:

class Foo
{
public:
     Foo();
     Foo(int val);
}; 

Foo::Foo()
{
     Foo(1);
}

Foo:Foo(int val)
{
     std::cout << val;
}

This doesnt compile for me. I am trying to create 2 constructors one witch takes parameter and one that sets it as default (the void one). I would aprichiate all help.

2

There are 2 answers

0
Bastien On BEST ANSWER
class Foo
{
public:
     Foo();
     Foo(int val);
}; 

Foo::Foo() : Foo(1)
{
}

Foo:Foo(int val)
{
     std::cout << val;
}
0
nvoigt On

It's called constructor delegation:

class Foo
{
public:
     Foo();
     Foo(int val);
}; 

Foo::Foo() : Foo(1)
{
}

Foo:Foo(int val)
{
     std::cout << val;
}

In this case you could also use default parameters:

class Foo
{
public:
     Foo(int val = 1);
}; 

Foo:Foo(int val /* = 1 */)
{
     std::cout << val;
}