Archived

This topic is now archived and is closed to further replies.

Chris41411

Help with object on the freestore

Recommended Posts

Someone help me out here.
#include <iostream>
#include <cstdlib>


using namespace std;

class Cat
{
public:
	Cat();
	~Cat() {}
	void SetAge(int a) { age = a; }
	void GetAge() { cout << age << endl; }
private:
	int age;
};

Cat::Cat():
age(1)
{

}

int main()
{
   Cat * Frisky = new Cat;
	Frisky->SetAge(5);
	Frisky->GetAge();

	cout << &Frisky << endl;

	Frisky = new Cat;
	Frisky->GetAge();
	
	cout << &Frisky << endl;

	system("pause");
	return 0;
}
What is happening to the original new cat? My compiler says that the address of the second new cat is the same as the first. Should this be happening?

Share this post


Link to post
Share on other sites
The address is the same becuase the variable is the same. By doing &Frisky you get the address of the *variable* Frisky, not the address of the Cat object. The variable Frisky *contains* the address of the Cat objects so to see the different addresses you would have to do


int main()
{
Cat * Frisky = new Cat;
Frisky->SetAge(5);
Frisky->GetAge();
cout << (int)Frisky << endl;
Frisky = new Cat;
Frisky->GetAge();
cout << (int)Frisky << endl;
system("pause");
return 0;

}



:::: [ Triple Buffer ] ::::

Share this post


Link to post
Share on other sites