Thread: returning a constructor?

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    113

    returning a constructor?

    //hi i saw an example of the + operator overloaded and i see that that operator+ function returns a constructor what is the logic behind this?

    Code:
    Class MyClass{
          public:                  
               MyClass(int);//constructor     
                ...   
              //+ operator overloaded
              MyClass operator+(const MyClass &objetc)const
             {
                 //how this can work and why?
                  return MyClass(localData + object.localData)
             }
              ...
    };
    
    int main()
    {
         MyClass n1;
         MyClass n2(20);
         Mclass n3(6);
             
         n1 = n2+n3;
         return 0;
    }
    thanks for any help

  2. #2
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    It's a form of optimization. In the code you have listed you can return anything that resolves to a MyClass object. Clearly, the MyClass constructor will return a MyClass object which can then act as the return object for + operator. It's sort of like using isalpha() in the following syntax:
    Code:
    char myString[] = "hello world";
    char ch;
    for(int i = 0; i < strlen(myString); ++i)
    {
       if(isalpha(ch))
    	 cout << "element " << i << " of myString is a letter" << endl;
       else
    	 cout << "element " << i << " of myString isn't a letter" << endl;
    }
    here, isalpha() returns a value that can be interpretted as true or false, which is what if() is looking for, so it works just fine.

  3. #3
    Registered User
    Join Date
    Mar 2004
    Posts
    113
    good ,
    thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 06-10-2008, 08:38 PM
  2. C++ have a constructor call another constructor
    By QuestionC in forum C++ Programming
    Replies: 4
    Last Post: 05-17-2007, 01:59 AM
  3. Replies: 3
    Last Post: 03-26-2006, 12:59 AM
  4. Can Someone Translate this text
    By lanh215 in forum C++ Programming
    Replies: 24
    Last Post: 01-17-2006, 10:02 AM
  5. Need help in classes
    By LBY in forum C++ Programming
    Replies: 11
    Last Post: 11-26-2004, 04:50 AM