whats wrong with it ? can any one explain pls

0 Alam Khattak · January 3, 2015
/images/forum/upload/2015-01-03/0b05da15565bac84c001849309feddff.jpg

Post a Reply

Replies

Oldest  Newest  Rating
+3 Laura Lee · January 3, 2015
Yes, the problem is your "addNumbers" function doesn't have a return datatype.
Since you're returning an integer, the addNumbers function should be of int datatype.

int addNumbers(int x, int y)
{
return x+y;
}
0 Alam Khattak · January 4, 2015
/images/forum/upload/2015-01-04/7074a9b425a5dee21f9d74c6a36f4cde.jpg
0 Alam Khattak · January 4, 2015
still giving error
+1 Laura Lee · January 4, 2015
cout << AlamsObject.addNumbers(36,21);
0 Alam Khattak · January 4, 2015
thanks Laura Li
0 Alam Khattak · January 4, 2015
i made a class and create constructor in it. 
Now in the main when i create the object as like Bucky said that the constructor command will be printed automatically.but it does not .instead gave an error. 
here is the program 

#include <iostream> 

using namespace std; 
class AlamsClass{ 
public: 
AlamsClass(){ 
cout << "this will get printed automatically"} 

}; 
int main() 

AlamsClass ao; 
+1 Franz Schmidt · January 4, 2015
You forgot a semicolon in your constructor:

#include <iostream>
using namespace std;

class AlamsClass{
  public:
     AlamsClass(){
        cout << "this will get printed automatically";
     }
};

int main(){
  AlamsClass ao;
}
0 Alam Khattak · January 4, 2015
oh thanks Franz u r such a nice :)guy
0 Franz Schmidt · January 4, 2015
you just need to take the code from the add function and make it a constructor and require parameters in your constructor

e.g.:
#include <iostream>
using namspace std;
class AlamsClass(){
  private:
     int answer;
  public:
     AlamsClass(int x, int y){
        answer = x + y;
     }
     int getanswer(){
        return answer;
     }
}
int main(){
  AlamsClass ao(3, 5);
  cout << ao.getanswer();
}


Or if you want to use the add function itself:
#include <iostream>
using namespace std;
class AlamsClass(){
  private:
     int answer;
  public:
     void addNumbers(int x, int y){
        answer = x + y;
     }
     AlamsClass(int x, int y){
        addNumbers(x, y);
     }
     int getanswer(){
        return answer;
     }
}
int main(){
  AlamsClass ao(3, 5);
  cout << ao.getanswer();
  ao.addNumbers(3, 8);
  cout << ao.getanswer();
}

The advantage of this is you can call the add function in your main too.
  • 1

C++

107,188 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator