Is calling method from class constructor okay?

Started by
5 comments, last by Zahlman 17 years, 10 months ago
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
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).
屋根を固定するために何パンケーキそれは取るか。紫色、ヘビに足がないばい。
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 :)
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).
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.
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).
- 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.

This topic is closed to new replies.

Advertisement