2

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Aadil Hoda
  • 592
  • 7
  • 17
  • 4
    Most certainly a good duplicate on this, but essentially the presence of your constructor deletes the default one. You can re-introduce with `NoDefault() = default;` – Bathsheba Apr 20 '22 at 07:19
  • 1
    consider you create a `NoDefault` in `main` (not as member of some class). You can only create it by calling its constructor. When it is a member of a different class it is similar. – 463035818_is_not_an_ai Apr 20 '22 at 07:24
  • 1
    c++ simply doesn't allow uninitialised objects, it makes everything much simpler, the compiler knows every object was initialised so it can run the destructor on every object when it's destroyed, otherwise it'd have to somehow keep a flag for every object to track whether it was initialised or not – Alan Birtles Apr 20 '22 at 07:24
  • @Bathsheba However, you shouldn't just add a default constructor to an object if another object depends on it fail to default construct. Instead, add a default member initializer to `A`. So in `A`, you would have `NoDefault my_mem = {"hello"};` – Ranoiaetep Apr 20 '22 at 07:40
  • It's not because there is a member class type but because there is a custom constructor, which disable the default one. – Moia Apr 20 '22 at 07:41

1 Answers1

5

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.)

songyuanyao
  • 169,198
  • 16
  • 310
  • 405