Question about Constructors

+1 Lé Pig · December 28, 2014
If this is how you call for for strings in the program using constructors....


class ClassOne{
public:
  ClassOne(string z){
    setName(z);
  }
  void setName (string x){
    name = x;
  }
    string getName(){
        return name;
    }
private:
    string name;
};

Then why does using addition and integers not require or allow you to use the void variable "addNumbers" like when using strings??


class ClassOne{
public:
  ClassOne(int a, int b){
    answer = a + b;
  }
  void addNumbers (int c, int d){
    answer = c + d;
  }
    int getAnswer(){
        return answer;
    }
private:
    int answer;
};

Thank you!!

Post a Reply

Replies

Oldest  Newest  Rating
0 Franz Schmidt · December 28, 2014
Ok I think I didn't understand your question at all...:ermm:
First of all the void variable "addNumbers" is not a variable. It's a FUNCTION. Sorry for correction but this is a really important part of programming to make a differenze between those two things.

Second if I understood everything right your question is why I can use this with strings:

ClassOne(string z){
setName(z);
}
void setName (string x){
name = x;
}

and can't use this with integers:

ClassOne(int a, int b){
addNumbers(a, b);
}
void addNumbers (int c, int d){
answer = c + d;
}



But both methods are possible you can eather use the private variable answer or the public function addNumbers. The result will be the same.:D

If it didn't work for you could you please post the error message?
0 Lé Pig · December 29, 2014
Thank you! And please correct me I won't be offended????. So the type is void and the function is "addNumbers"??  It is definitely these little things I aim to understand. Thanks again!
0 Franz Schmidt · December 29, 2014
Ok :D
Just for better understanding the the syntax of a function is:
void func_name (int parameter){}

the "void" at the beginning is the return type (in this case nothing ^^)
and then there's the function name. This is the name you call in the main
in brackets there are the parameters. You can declair as much as you need. If you don't declair any parameter you can leaf it empty or just type in void as well
Between the curly brackets is your function body, where you write your code for the function

For more infos look up here: http://www.cplusplus.com/doc/tutorial/functions/
  • 1

C++

107,026 followers
About

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

Links
Moderators
Bucky Roberts Administrator