• Advertisement
Sign in to follow this  

Is calling method from class constructor okay?

This topic is 4277 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

My compiler will allow me to call a method of a class from the class constructor. However, I was wondering if this is one of those "Yes, but don't do it" things. I think I've read somewhere that this is one of those cases. Below is a simple example. In practice the method(s) I would call from the constructor would be doing more complex stuff based on data passed to the constructor.
class MyClass
{
    public:
        MyClass();
  
        void SetX();
    private:
        int x;
};

MyClass::MyClass()
{
    SetX();
}

void MyClass::SetX()
{
    x = 42;
}

Thanks, Eugenek

Share this post


Link to post
Share on other sites
Advertisement
I'm kind of strange in that I always have a seperate "setup" method in a class instead of having the constructor do much beyond the very bare minimums (sometimes that's nothing at all).

Share this post


Link to post
Share on other sites
You should never call a virtual class method from a constructor. Otherwise I think you should be safe. The reason not to do it with virtuals is because the pointer-table used to look up those methods might not have been initialized yet. Your example should work just fine I believe :)

Share this post


Link to post
Share on other sites
I try to do as little work in the constructor as possible. It makes it harder to recover from failure otherwise (especially if we're talking about globals and such things).

Share this post


Link to post
Share on other sites
With exception of virtual functions maybe, this is both common and "the right" thing to do.
Its an example of code re-use which is a good thing.
The same goes for the destructor.

Share this post


Link to post
Share on other sites
As pulpfist stated, this is a good thing. Just don't do anything in the called method(s) that can fail (unless they handle clean recovery themselves).

Share this post


Link to post
Share on other sites
- Don't call a virtual function.
- Don't call a function that will inspect or mutate members that haven't yet been initialized by the constructor. (But you normally *should not have this problem*, because you should be doing initialization with the constructor initialization list anyway.)

Otherwise you are fine.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement