2

I want to create a class that has an object (not a pointer) of another class as a private member. The other class accepts creating class's this pointer as constructor argument. However, I cant pass this from creating class's .h file as it shows a compile error. Of course, I can declare a pointer in the .h and new it in creating class's .cpp file and pass this as a constructor argument, but in this case I will be creating a pointer and not an object. I want to know how to create such an object?

class MyClass
{

private:
    Parent* m_parent {nullptr};

public:
    MyClass (Parent* parent) //The non-default constructor I want to invoke
    {
    m_parent = parent;
    }
};

MyCode.h

class Parent
{

/*This class wants to have a private member object of type MyClass
and it wants to create this object by invoking its non-default parameter
and pass "this" as a parameter.
*/

private:
    MyClass myclass; 
//OPTION 1: This will invoke default constructor of MyClass, which I dont //want
    Parent();
};

MyCode.cpp

Parent::Parent()
{
/*
Here I can create MyClass object and use its non-default constructor
However, the scope of this object is local and inaccessable outside of  function
*/

    MyClass myclass(this); //OPTION 2: this will invoke non-default constructor of myClass

}
sashoalm
  • 75,001
  • 122
  • 434
  • 781
bsobaid
  • 955
  • 1
  • 16
  • 36
  • 1
    Sorry, but this question doesn't show basic research about initializer lists. – underscore_d Feb 02 '16 at 16:25
  • This is effectivly another instance of this question: http://stackoverflow.com/questions/7507526/initializing-a-member-class-of-an-object-using-a-non-default-constructor-in-c?rq=1 – PeterSW Feb 02 '16 at 18:04

1 Answers1

3

You can use member initializer list to specify which ctor to be invoked.

In MyCode.cpp,

Parent::Parent() : myclass(this) {}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • in the MyCode.h file? – bsobaid Feb 02 '16 at 15:07
  • No, in `MyCode.cpp`. – songyuanyao Feb 02 '16 at 15:08
  • ok, so I declare the object in MyCode.h file as I have and then in .cpp file I use the member init list. That will make sure only 1 myclass object is created by callings myclass's non-default constructor, correct? – bsobaid Feb 02 '16 at 15:11
  • @bsobaid Correct. You declare it and then initialize it in the ctor with member init list. – songyuanyao Feb 02 '16 at 15:12
  • some compilers, at least VC++, throw a warning that it's dangerous to use "this" in member initialiser list. The reason is that the object is not constructed yet and so its potential usage in child's constructor (something more than just saving a pointer or reference) would lead to UB. – Andriy Tylychko Feb 02 '16 at 17:45