#include <iostream>

using namespace std;

class person
{
   private:
   string name;
   int age;

   public:
   person(const string &getname):
              name(getname), age(0){ }

   void addAge(const string &getname)
   {
      age++;
   }

   void getAge(void)
   {
      cout << endl;
      cout << name << " now " << age << " years old";
   }

};


int main()
{
   person *p;
   p = new person("John");
   p->addAge("John"); 
   p->addAge("John");
   p->addAge("John");
   p->getAge(); //3

   p = new person("Connor");
   p->addAge("Connor");
   p->getAge(); //1

   *p = person("John");
   p->addAge("John");
   p->getAge();      //John age start at 1 again????

   cout << endl;

   return 0;
}

How do I increase John age, after I insert new person???
can anyone help me please.
Thank You

By not using 'P' again for the new person "john".

Or remove this line *p = person("John"); if the two john's are one and the same person. You'll still have to use another variable name for "conner" though.

What you're doing is actually something like this:

int a = 5;
a = 3;
a = 10;

And then you wonder why 'a' isn't 5 anymore.

Also: Do you realize that passing a name to the "addAge" doesn't do anything?

Apart from that . The using of new operators and not deleting them is causing a memory leak everytime you run your code.

>Apart from that . The using of new operators and not deleting them is causing a memory leak everytime you run your code.
Absolutely correct! But normally today's Operating Systems clean up the memory automatically when the program exits, however, allocating memory and not releasing it back is not a good programming practice, don't rely on the OS to do the memory cleanup for you !

This article has been dead for over six months. Start a new discussion instead.