dynamic allocation problem

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <cmath>

using namespace std;

struct points
{
	double x1;
	double x2;
	double y1;
	double y2;
};

int main()
{
	points *structObj; //<- why doesnt this work
	//why do i need to dynamically allocate it
	points *structObj = new points;
	
	cout << "Enter a x1: ";
	cin >> structObj->x1;
	

	
	delete structObj;
	
	return 0;
}
structObj is a pointer. structObj->x1 accesses the x1 value of the object that structObj is pointing to. If structObj is not pointing to a valid object this piece of code will obviously not work correctly.

If you don't want to use dynamic allocation you can simply declare structObj as a regular variable instead of a pointer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cmath>

using namespace std;

struct points
{
	double x1;
	double x2;
	double y1;
	double y2;
};

int main()
{
	points structObj;
	
	cout << "Enter a x1: ";
	cin >> structObj.x1;
	
	return 0;
}
delete structObj;
with std::unique_ptr<> or std::shared_ptr<> such statements are no longer required. Also ctor overloading and make_unique<> (or make_shared<>) can initialize the owned object in one go:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# include <iostream>
# include <memory>
# include <string>

//using namespace std;
//https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice

struct Point
{
	double m_x;
	double m_y;
	std::string m_justForIllustration;

	Point (const double x, const double y, const std::string& illustration)
	: m_x(x), m_y(y), m_justForIllustration(illustration){}
	~Point(){std::cout << "goodbye: " << m_justForIllustration << "\n";}
};

int main()
{
	auto point_unique_ptr = std::make_unique<Point>(1.2, 3.4, "helloWorld");
	//program prints "goodbye: helloWorld" from the dtor
}

Topic archived. No new replies allowed.