I have been told over and over again to keep my class variables private because keeping them public would be bad coding practice, so to hit that nail on the head that is what i have been doing from day one. I never had any problems while I had all the code on one page, but now I get an undefined error when I try and use a function to access my private variable.
in my classs.h
class classs
{
public:
classs(void);
void setAge(int x);
int getAge();
private:
int age;
};
then in my classs.cpp i have:
void setAge(int x)
{
age = x;
}
and
int getAge()
{
return age;
}
here it is telling me that age is undefined. I never had any problems when all of this code was in one .cpp (main.cpp). I have also #include classs.h on my classs.cpp
This is happening not because your
setAgedefinition is in a different file, but because it is now outside theclass classs {}block. The compiler doesn’t have any way to know thatsetAgeis a member of the class, so it doesn’t have the class’s attributes in scope.Fix it by declaring your function as
classs::setAge