1

In the below example, I initialize obj with itself.

#include <iostream>

class base {
public:
    base()
    {
        std::cout << "base" << std::endl;
    }

    base(const base& obj)
    {
        std::cout << "copy base" << std::endl;
    }

};

int main ()
{
    base obj = obj;
}

This program prints "copy base".
Why default constructor isn't called?
Why there is no error?
Why is it allowed?

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • Why would you do this? You are trying to initialize a new object with itself. Surely this is undefined behavior. – paddy Jul 14 '20 at 05:10
  • You could call `base::base()` from `base::base(const base &)` with a _delegating constructor_. See [this answer](https://stackoverflow.com/a/308318/1563833). – Wyck Jul 14 '20 at 05:11
  • 1
    What is obj? Does this code compile? – Itumeleng Tlali Jul 14 '20 at 05:11
  • This code shouldn't even compile. Please share the shortest working example. But the default constructor gets called if you do the following base obj; – Anirudh Jul 14 '20 at 05:17
  • 1
    @ItumelengTlali `obj` is a `base`, and the definition of `base` is right above `main`. It compiles if you add `#include `. – molbdnilo Jul 14 '20 at 05:18
  • 4
    Does this answer your question? [Object that initializes to itself in C++](https://stackoverflow.com/questions/31759210/object-that-initializes-to-itself-in-c) (see the second answer) – Lukas-T Jul 14 '20 at 06:05
  • ... and some `std::*`, sandeep please provide a [mre], with the emphasis on "reproducible". We should be able to copy-paste your code and run it without further modifications. – Lukas-T Jul 14 '20 at 06:06

0 Answers0