Home > Net >  Why member of class type needs initialization?
Why member of class type needs initialization?

Time:04-20

I am reading about constructors in C . I came across this example:

#include <iostream>

using namespace std;

class NoDefault
{
    public:
        NoDefault(const std::string&);
};

struct A
{
    NoDefault my_mem;
};

int main()
{
    A a;
    return 0;
}

It is giving this message on compilation:

main.cpp:26:7: error: use of deleted function ‘A::A()’

I can get a intuitive feeling that the default ctor is deleted because there is a member of class type inside the struct A. I want to ask why there is a necessity to initialize the class type member? Can we not leave it uninitialized?

Maybe very trivial question, but I am curious about the thinking behind designing it that way? I am new to OOP.

CodePudding user response:

A a; performs default initialization; a gets default-initialized, and its member my_mem gets default-initialized too. For class type, that means the default constructor will be used for the initialization but NoDefault doesn't have it, which leads to the error. (Behaviors are different for built-in types. In default-initialization they might be initialized to indeterminate values.)

  • Related