Search code examples
c++this-pointerobject-construction

c++ this pointer question


here is the thing, I want to (probably not the best thing to do) have the ability to call some class constructor that receives as a parameter a pointer to the class who's calling (ufff!!!). Well in code looks better, here it goes, as I do it in C#.

public class SomeClass
{
   SomeOtherClass someOtherClass;

   //Constructor
   public SomeClass(SomeOtherClass someOtherClass)
   {
      this->someOtherClass = someOtherClass;
   }
}

public class SomeOtherClass
{

   public SomeOtherMethod()
   {
      SomeClass c = new SomeClass(this);
   }
}

So, How can I achieve the same result in c++? Thanx in advance.


Solution

  • probably not the best thing to do

    It might not be a bad idea. However, every time you use pointers in C++, you must be completely clear about how it will be used: what kind of thing is being pointed to (not just the type of the pointer, but scalar vs. array, etc.), how the pointed-at thing gets there (e.g. via new? As part of some other object? Something else?), and how it will all get cleaned up.

    How can I achieve the same result in c++?

    Almost identically, except of course that C++ does not use new when you create a local instance by value (so we instead write SomeClass c = SomeClass(this);, or more simply SomeClass c(this);), and we must be aware of the pointer vs. value types (so SomeClass::someOtherClass is now a SomeOtherClass *, which is also the type we accept in the constructor). You should also strongly consider using initialization lists to initialize data members, thus SomeClass::SomeClass(SomeOtherClass* someOtherClass): someOtherClass(someOtherClass) {}.