tags:

views:

55

answers:

4

Hi,
Let me consider the following example!

namespace nSpace {  
  class Addition {  
    int val1;  
    int val2;  
  public:  
    Addition(int firstVal, int secondVal) {  
      this.val1 = firstVal;  
      this.val2 = secondval;  
    }  
    void sum() {  
      cout<<"sum of val1 and val2 = " <<this.val1 + this.val2<<"\n";  
    }  
  };  

  Addition Addobj = new Addition(2, 3);  // Is it possible ? if not, any other way ?  
  Addobj.sum();  
}  

If not, do let me know the reason.

Thank you!

A: 

yes It is possible, Only the objects at namespace level is possible, but you can't have a executing statements,

 Addition Addobj = Addition(2, 3);  // Is valid
 Addobj.sum();  //not valid
//You got few error, below is working code
namespace nSpace {  
  class Addition {  
  int val1;  
  int val2;  
 public:  
   Addition(int firstVal, int secondVal) {  
    this->val1 = firstVal;  
    this->val2 = secondVal; 
     cout<<"sum of val1 and val2 = ";
  }  
  void sum() {  
   cout<<"sum of val1 and val2 = " <<this->val1 + this->val2<<"\n";  
  }
  } ;
 Addition Addobj =  Addition(2, 3);  // Is it possible ? yes  
 //Addobj->sum();// this does not work

} 
void main()
{

}
yesraaj
A: 

You cant with posted code. the reason is simple, you are not within any function body to execute ur code. the new() operator and function sum() cannot be called as lhs at global level

YeenFei
You're gonna have to stop using "ur" if you want to sound reasonable. :)
GMan
Actually you can use a new operator outside a function provided it is part of a variable definition. You can actually invoke any code arbitrary code outside of function if it's being done to define a variable (for example `time_t startup = time(0);` is legal outside a function).
R Samuel Klatchko
+1  A: 

This isn't Java, you just need the line

Addition Addobj(2, 3);
rlbond
A: 

This is legal outside a function:

Addition *Addobj = new Addition(2, 3);

because that is considered a variable definition and it may be done outside of a function (it will define a global variable). Note that since you are using new, the type of variable actually has to be a pointer;

This on the other hand is not legal outside a function

Addobj->sum();  // Illegal outside a function

The reason why is that this is a statement. Both statements and expressions are only legal inside a function.

R Samuel Klatchko