Search code examples
c++class-constructors

"this" Cannot Be Used As A Function


In C++ I'm attempting to emulate how Java handles calls to it's constructor. In my Java code, if I have 2 different constructors and want to have one call the other, I simply use the this keyword. Example:

public Constructor1(String s1, String s2)
{
    //fun stuff here
}

public Constructor2(String s1)
{
    this("Testing", s1);
}

With this code, by instantiating an object with Constructor2 (passing in a single string) it will then just call Constructor1. This works great in Java but how can I get similar functionality in C++? When I use the this keyword it complains and tells me 'this' cannot be used as a function.


Solution

  • You can write an init private member function for such job, as shown below:

    struct A
    {
       A(const string & s1,const string & s2)
       {
           init(s1,s2);
       }
       A(const string & s)
       {
          init("Testing", s);
       }
    private:
    
       void init(const string & s1,const string & s2)
       {
             //do the initialization
       }
    
    };