Jump to content
  • Advertisement

Archived

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

Chris41411

Help with object on the freestore

This topic is 5353 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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

int* p1 = new int;
int* p2 = new int;

delete(p1);
delete(p2);



You are sure p1,p2 are different


int* p1 = new int;
delete(p1);

int* p2 = new int;
delete(p2);


p1 and p2 can be equal (your case)



Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!