Constructor call inside Constructor.

In the below code I am trying to call a constructor of another Class in MyClass constructor. Its working fine.
But my question is this a right way to do it or assign with Initializer list.


1
2
3
4
5
6
7
8
9
10
11
12
13
class MyClass
{
    AnotherClass* var;
public:
       MyClass()
       {
           var = new AnotherClass(); // IS this Valid
       }
       ~MyClass()
       {
           delete var;
       }
}


Edit: Thanks jsmith
Last edited on
The above code can't compile since var is not a pointer (lines 7 and 11 should be compile errors).
If "var" is simply an instance of AnotherClass and not a pointer, then the correct way (and
technically the only way) to initialize is through the initializer list.

(Note that C++ makes a distinction between "initializing" and "assigning" that most average
incorrectly programmers ignore.)
either
1
2
3
4
5
6
7
8
9
10
11
12
13
class MyClass
{
    AnotherClass* var;
public:
    MyClass()
    {
        var = new AnotherClass();
    }
    ~MyClass()
    {
        delete var;
    }
}

or
1
2
3
4
5
6
class MyClass
{
    AnotherClass var;
public:
    MyClass() : var() {}
}

or
1
2
3
4
class MyClass
{
    AnotherClass var;
}
since they all are default constructors.
OR:
1
2
3
4
5
6
7
8
9
10
class MyClass
{
    AnotherClass* var;
public:
    MyClass() : var(new AnotherClass()) {}
    ~MyClass()
    {
        delete var;
    }
}
Topic archived. No new replies allowed.