c++constructoroperator-overloading

Invoking overload constructor within constructor


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 trying to do:

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

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

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

This doesn't compile for me. I am trying to create 2 constructors one which takes a parameter and one that sets it as default (the void one).


Solution

  • class Foo
    {
    public:
         Foo();
         Foo(int val);
    }; 
    
    Foo::Foo() : Foo(1)
    {
    }
    
    Foo:Foo(int val)
    {
         std::cout << val;
    }