0

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?

  • Add a proper copy constructor. – danielschemmel Jan 29 '15 at 22:19
  • Search for the so-called "Law of Three". – Ulrich Eckhardt Jan 29 '15 at 22:20
  • Why are you using (raw) pointers at all? At least use [smart pointers](http://en.cppreference.com/w/cpp/memory), instead of bothering with this yourself. – πάντα ῥεῖ Jan 29 '15 at 22:24
  • The wikipedia page for copy constructor will help you. – Paul Rooney Jan 29 '15 at 22:28
  • You should read [What is The Rule of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) to get a better understanding. Pretty much, the compiler has created a default copy constructor for you. Each time you add a vector element, an object is created, and copy constructed. However, the default copy is pretty simple, so a pointer just gets copied. So in your vector objects, m is actually a copy of a pointer to another object. . which gets destroyed and so that memory is freed. So when you get around to using it, it refers to junk. – iheanyi Jan 29 '15 at 22:28
  • 1
    `I am familiar enough with C, so it's always okay to explain me in C terms if possible` If you only know `C`, in no way will you know what a copy constructor or assignment operator are. – PaulMcKenzie Jan 29 '15 at 22:29

0 Answers0