Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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.

like image 446
Sam Youtsey Avatar asked Dec 03 '22 07:12

Sam Youtsey


2 Answers

This will be possible in C++11 with constructor delegation:

class Foo {
public:
    Foo(std::string s1, std::string s2) {
        //fun stuff here
    }

    Foo(std::string s1) : Foo("Testing", s1) {}
};
like image 68
R. Martinho Fernandes Avatar answered Dec 20 '22 16:12

R. Martinho Fernandes


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
   }

};
like image 43
Nawaz Avatar answered Dec 20 '22 17:12

Nawaz