calling member functions from within the constructor

Jul 24, 2009 at 2:37pm
1. Is it bad practice to call member functions from inside the constructor?

2. Is it bad practice to call member functions from inside other member functions?
Jul 24, 2009 at 2:38pm
1. 2. No
Jul 24, 2009 at 2:48pm
One more question...

If you create an object and a parameter (lets say a std::string) needs to be passed to the constructor, is there any way of letting the user use their own string? e.g.

1
2
3
    std::string str;
    std::getline(cin, str);
    Password obj(str4);


Whereby password is the name of the class and obj is the object created.
Jul 24, 2009 at 2:51pm
You can put whatever string you want as the parameter.

If you want the user to enter the data for the parameter:
1
2
3
std::string str;
std::getline(cin, str);
Password obj(str);
Jul 24, 2009 at 3:01pm
Ok sorry, I thought I tried that and got an error but I just re-did it and it was fine. Thanks both of you!
Jul 24, 2009 at 3:30pm
To clarify one of the original questions.

1. It is fine to call non-virtual methods from the constructor.
Jul 24, 2009 at 3:49pm
Yeah that's what I meant, I haven't covered virtual-methods yet. For when I do though, why can't/shouldn't you call virtual methods?
Jul 24, 2009 at 3:57pm
Because the vtable isn't built completely by the time the constructor is called.

On a similar note, the same problem happens with virtual functions and destructors.

Basically you shouldn't/can't call members of derived classes from the parent's ctor/dtor.
Topic archived. No new replies allowed.