Lesson 13 Q: I thought you had to set the variable type before you could assign it a value?

+1 Melissa Eaton · May 15, 2015
In past lessons, you said that you have to declare the type of a variable before assigning it a value; for instance, if I don't want to say "int x=3" right away, I can just split it up and say "int x" a few lines before putting "x=3". At least, that's how I understood it-- that you have to tell the program what type a variable is before you can set a value?

Anyway, in this video, it looks like you don't tell the program that the variable "name" is a string type until 6 lines AFTER you've already assigned "name" a value, "name=x". Can someone elaborate on this a little?

Post a Reply

Replies

Oldest  Newest  Rating
0 Sengngy Kouch · May 15, 2015
Hi, Melissa Eaton!

I wonder if this is your question:


class BuckysClass {

public:
void setName (string x){
name = x;
}
private:
string name;

};



If I do not misunderstand your question, below should be the explanation.




because this is the class that you are created, there is usually Private and Public. 

It doesn't matter which one your put first, Private on top, then Public or vise versa. 

As a result, in this class. It does not matter where you declare your "NAME". it will know where is it because it is in the scope of the class "BuckysClass". 

Plus setName is a function, it will search around for variable "NAME" in its scope. If there is one, it will run and compile.

Note:  this only happens in Class. 


If you try this in main function.

Example
int main(){
name = "Melissa";

string name;

return 0;
}




it will fail.




I hope this won't confuse you even more!! ^^
  • 1

C++

107,303 followers
About

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

Links
Moderators
Bucky Roberts Administrator