Quick Question On Constructors

closed account (zb0S216C)
Can I call a member method in a constructor? Here's a quick example that shows what I mean if you don't already:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct STRUCT
{
    STRUCT( void )
    {
        InitX( 7 );
    }
   
    int X;
    
    void InitX( const int Init )
    {
        X = Init;
    }
};


Much appreciated.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class ClassName
{
    private:
        DataType VariableName;
    public:
        void Methods;
        ClassName();
        ~ClassName(){};
};

ClassName::ClassName()
{
    VariableName = Value;
}


I threw that together really quick.
A constructor can only set a variable to default values. I don't think it will work for methods.
Last edited on
closed account (zb0S216C)
Thanks, Khaltazar. It makes sense that destructors can call member methods but constructors calling member methods didn't seem correct.

Thanks for clearing that up for me.
A constructor can call any non-virtual method. However, keep in mind that assignment and initialization are two different things in C++. In OP's original example, a better way to do that would be:

1
2
3
struct S {
    S() : X( 7 ) {}
};


using an initializer list instead of an assignment.

closed account (zb0S216C)
I do agree that assignment and initialization are two different things. So, S() : X( 7 ) is initialization not assignment?
Last edited on
Yes. Assignment always uses an explicit equals sign.

[EDIT: But not all equals signs are assignments.]
Last edited on
I almost always add a private function named void Init() and I call it in every constructor and operator = . It makes initialization of many variables simple.
Fortunately C++0x provides delgating constructors which obviate the need for such an Init method call in the constructor.
http://www2.research.att.com/~bs/C++0xFAQ.html#delegating-ctor

However, operator= calling an Init() method will provide only the basic exception guarantee, which is generally not preferred when a better implementation exists that provides a strong guarantee. See http://www.cplusplus.com/forum/articles/18749/ for details on an exception-safe (providing strong guarantee) assignment operator.
Thanks, I'll check it out!
Topic archived. No new replies allowed.