0

Is it is possible to create an object of a class like below which does not have any parameterless constructor? Passing null pointer is not an option I think.

class MyClass
{
public:
    MyClass(MyClass* myClass)
    {
        //do something
    };
};
Arun K
  • 413
  • 4
  • 15
  • 7
    Question is why do you need that? – πάντα ῥεῖ Mar 07 '22 at 10:42
  • 3
    "_Passing null pointer is not an option I think._": Why not? – user17732522 Mar 07 '22 at 10:43
  • If a `nullptr` is not an option, you're better off passing in the argument as a reference; at that point you've just created the copy constructor with extra steps. – Casey Mar 07 '22 at 10:44
  • You might need a nullptr to create the first object, and then pass that on when creating the next one. For example, a linked list might end in a nullptr. – BoP Mar 07 '22 at 10:46
  • 1
    https://stackoverflow.com/questions/32608458/is-passing-a-c-object-into-its-own-constructor-legal – Arun K Mar 07 '22 at 10:48
  • 1
    You *could* say `MyClass x(&x);` but you can't do anything with that object in the constructor. Is this an academic exercise, or are you planning to actually do this? – molbdnilo Mar 07 '22 at 10:48
  • Hmm. How would you create the object whose address you pass to the constructor that creates another object? At some point, there must be an "original", is not? – Adrian Mole Mar 07 '22 at 10:54
  • the title is not quite clear. "with its own object as parameter" do you want to create an object called `a` and pass `&a` as parameter to the constructor? Or is the question merely about the `MyClass*` argument? – 463035818_is_not_an_ai Mar 07 '22 at 10:56
  • 2
    "is it possible?" you better try out and see what happens. When you have code with a compiler error it is much simpler to help you. Currently the question is unclear – 463035818_is_not_an_ai Mar 07 '22 at 10:57

0 Answers0