user3275730
user3275730

Reputation: 25

class not working properly

Im still trying to learn classes, but I created this and I seem to be getting some weird number like a memory number or some thing and i cant figure out whats wrong.

#include <iostream>
#include <string>
using namespace std;

class JoesClass {
public:
    int setAge(int age) {       
        return age;
    }

    void displayAge() {
        cout << "your age is " << age << endl;  
    }
private:
    int age;
};

int main()
{
    JoesClass newobject;
    newobject.setAge(40);
    newobject.displayAge();

    return 0;
}

Upvotes: 1

Views: 102

Answers (3)

bblincoe
bblincoe

Reputation: 2483

You are just returning the age that the caller passes in. You need to set the object's age member variable to that value.

void setAge(int age)
{
  this->age = age;
}

this is used to prevent variable hiding (your member variable is named "age" as well as the parameter name "age"). Which "age" are you referring to? That is where this can be used to explicitly state that "I want to use this object's age variable".

You may also want to wrap your displayAge method with a check for a valid age with something like the following:

void displayAge()
{
  if (age != 0)
  {
    std::cout << "your age is " << age << std::endl;
  }
}

and give your age variable a default value in the constructor:

JoesClass()
{
  this->age = 0;  // Initial value is considered not a valid age
}

Now when you create your class you'll have an initial value for age.

Upvotes: 3

Mike Seymour
Mike Seymour

Reputation: 254451

The problem is that this:

int setAge(int age) {
    return age;
}

doesn't set the age. It just returns the value you give it, without updating the class member. You want something more like:

void setAge(int age) {
    this->age = age;
}

You might want to change the argument name, so it doesn't hide the class member:

void setAge(int new_age) {
    age = new_age;
}

You should also get out of the habit of putting using namespace std; in the global namespace, and instead qualify standard library names like std::cout. While the using directive saves a bit of clutter, it can cause problems when you declare something with the same name as something in the library.

Upvotes: 6

Some programmer dude
Some programmer dude

Reputation: 409166

But, you're not setting the age variable in the setAge function. That means that the age member variable is uninitialized, and will contain a seemingly random value. Using uninitialized values leads to undefined behavior.

Upvotes: 0

Related Questions