Skip to main content
gamedev.net
🔒 Locked

pointers and classes

Started by Hop chewer 4 replies 700+ views
Original Post
Hop chewer
Hop chewer
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.
SiCrane
SiCrane
Rectangle * pointer_to_rect_C = &rectC
Hop chewer
Hop chewer
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.
rip-off
rip-off
What are you trying to achieve? In high level terms please.
Hop chewer
Hop chewer
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/
rip-off
rip-off
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.