I am learning C++, and currently confused with the constructor syntax. I am familiar enough with C, so it's always okay to explain me in C terms if possible.
The code below doesn't work at all. The member variables doesn't get initialized as expected. I can only see trash values somewhere in memory printed.
#include <cstdlib>
#include <iostream>
#include <vector>
class Point
{
struct M;
M* m;
public:
Point(int x, int y);
~Point();
void print();
};
struct Point::M
{
int x;
int y;
};
Point::Point(int x, int y)
: m {new M {x, y}} {}
Point::~Point()
{
delete m;
}
void Point::print()
{
std::cout << m->x << ' ' << m->y << std::endl;
}
int main()
{
const auto N = 5;
std::vector<Point> v;
for (auto i = 0; i < N; ++i)
{
v.push_back(Point(i, i + 1));
}
for (auto i = v.begin(); i != v.end(); ++i)
{
i->print();
}
return EXIT_SUCCESS;
}
But if I edit the main method as follows,
int main()
{
const auto N = 5;
std::vector<Point*> v;
for (auto i = 0; i < N; ++i)
{
v.push_back(new Point(i, i + 1));
}
for (auto i = v.begin(); i != v.end(); ++i)
{
(*i)->print();
}
return EXIT_SUCCESS;
}
besides that there is an obvious memory leak, the program works as intended without trash values.
What am I missing?