2

I was wondering if it is good programming to call a function from a constructor? For example:

class Foo{
    Foo(){
        function1();
    }

    void function1(){
    }
};
Anton Savin
  • 40,838
  • 8
  • 54
  • 90
  • 3
    As long as it's [not virtual](http://stackoverflow.com/questions/962132/calling-virtual-functions-inside-constructors). – Captain Obvlious Jun 03 '15 at 22:21
  • Take a look at http://stackoverflow.com/questions/26229680/behaviour-of-exception-handling-in-constructor-of-a-class to deal with functions called from constructors that throw exceptions. – R Sahu Jun 03 '15 at 22:24
  • Possible duplicate of http://stackoverflow.com/questions/4872707/calling-a-method-in-constructor – Alberto M Jun 04 '15 at 00:07

4 Answers4

1

If you want pure initialization function, you can handle that (in some cases) in a default constructor

class C
{
    C() { /* default init */ }
    C(int a) : C() { /* do something extra with a */ }
    C(const std::string& s) : C() { /* do something extra with s */ }
};
Zereges
  • 5,139
  • 1
  • 25
  • 49
0

This is definitely acceptable. Just make sure it is not a virtual function.

EDIT:

"virtual" not "pure virtual"

Josh Edwards
  • 369
  • 1
  • 4
0

This is a two part answer. From a technical point of view, sure it's fine, as long as it's not a virtual function.

From a conceptual point of view, it depends what the function does. If all it does is initialisation, then that's what your constructor is suppose to be doing. If it does more, and the function as a purpose outside of that and is being called from elsewhere also, then yeah, it can be a good thing.

Rosme
  • 1,049
  • 9
  • 23
-1

As long as it's not Virtual function it is acceptable.

Veitch
  • 1