Should I use a constructor only for variable initialization in C++?

Viewed 97

I am new to OOP in C++. I have a class that doesn't need to run any code neither does it need any parameter when the object is created, should I still write a constructor only for the initialization of the variables.
I can do this:

#include <iostream>

class Something
{
private:
    const char* msg = "Hewwo World"; // i can initialise here
public:
    void Print()
    {
        for (int i = 0; i < 11; ++i)
        {
            std::cout << *msg++;
        }
    }
};

int main()
{
    Something smth;
    smth.Print();
}

instead of this:

#include <iostream>

class Something
{
private:
    const char* msg;
public:
    Something()
    {
        msg = "Hewwo World";
    }
    void Print()
    {
        for (int i = 0; i < 11; ++i)
        {
            std::cout << *msg++;
        }
    }
};

int main()
{
    Something smth;
    smth.Print();
}

both give the same output and the first method is a lot cleaner (according to me). Is there any reason why I should use the second method?

2 Answers

in this particular code, you are not giving the class any parameters and there is no need of initializing the msg variable in a constructor. so, the constructor is not needed.

use the constructor when you want any variable to be initialized at the moment when the object is created or when you need to give some parameters to the class,then you can use the constructor.

const char* msg = "Hewwo World"; // i can initialise here

To be precise, you aren't initialising there. You're defning a default member initialiser. This initialiser will be used when you initialise an instance without providing an initialiser for that member.

should I still write a constructor only for the initialization of the variables.

Depends on case, but quite often there is no need to do that. Simple classes are often useful as aggregates. Precondition for a class to be an aggregate is that the class has no user declared constructors.

Related