How to access the Class Variables in the main function????

Hi everybody I am New to c++ programming..
I have written a code like like

class fruits
{
public:
int num;
public:
void color()
{
cout<<"the color is yellow:";
}
}f1;
main()
{
if(num==1)
f1.color();
else
cout<<"wrong number:";
}
here the variable "num"when i am using in main i am getting error although it has been declared as public variable.
can anybody tell me how to get out of the error????????
Then Why I am Getting errors as undeclared identifier "num"
Then Why I am Getting errors as undeclared identifier "num"


See your other almost identical thread. You're getting this error because you have not used the correct syntax for accessing a member of a class.

Once you've created an instance of a class, for example like this:

fruits aFruitObject;
you access the members like this:

aFruitObject.num;

Once you understand this, you can go on to learn about static class members which have different rules.
Last edited on
closed account (1vRz3TCk)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class fruits
{
public:
    int num;
public:
    void color()
    {
        cout<<"the color is yellow:";
    }
}f1;

main()  /* needs work */
{
    if(num==1)   /* f1.num perhaps */
        f1.color();
    else 
        cout<<"wrong number:";
}
your main() function should like this
main()
{
if(f1.num==1)
f1.color();
else
cout<<"wrong number:";
}

what's more,try to learn to use c++ definition,which define a object in main()!
!
main needs to return an int.
Topic archived. No new replies allowed.