Sign in to follow this  
Eugenek

Is calling method from class constructor okay?

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
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
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
- 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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this