Jump to content
  • Advertisement
Sign in to follow this  
Hop chewer

pointers and classes

This topic is 3499 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

Hello, I have created two objects.
[source lang= "cpp"]
//use of pointers with multiple objects
#include <iostream>

using namespace std;

class Rectangle
{
	private:
	int x, y;
	
	public:
	Rectangle();
	void set_values(int, int);	// must use arguments to set private data
	int area();
};

Rectangle::Rectangle()	//Constructor will initialize x and y when object rect is created
{						//That way if rect.area() is called before x and y are set, they will
	x = 0;				//be initialized.
	y = 0;
}

void Rectangle::set_values(int a, int b)
{
	x = a;
	y = b;
}

int Rectangle::area()
{
	return(x*y);
}

int main()
{
	Rectangle rectA;
	rectA.set_values(2, 10);
	cout << "rectA Area = " << rectA.area() << endl;
	
	Rectangle *rectB;
	rectB = new Rectangle;	//must create a new Rectangle object
	rectB->set_values(3, 10);
	cout << "*rectB Area = " << rectB->area() << endl;
	delete rectB;	//must delete object rectB when done
		
	return 0;
}

Now I want to create a third object: Rectangle rectC; After creating the object rectC, how would I make a pointer to this object? I am trying to do this without using new. pseudocode: Rectangle rectC; *rectC = rectC; I hope this makes sense.

Share this post


Link to post
Share on other sites
Advertisement
Thanks, that's just what I was looking for. One more thing. Is this third object the preferred method of for using pointers with multiple objects? I have seen several methods and am trying to use the most common method that others use.

Share this post


Link to post
Share on other sites
I am reading through the following tutorial and saw numerous ways to use pointers to objects. From a learning perspective I was just trying to understand what the accepted method is.
http://www.cplusplus.com/doc/tutorial/classes/

Share this post


Link to post
Share on other sites
There is no best method. It entirely depends on what you are trying to do. The best advice is to keep it simple.

If you can avoid using pointers, do so. Use values or references where possible.

If you can avoid using heap allocation, do so. If not, use smart pointers or similar objects to manage the deallocation.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

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

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!