Jaehyeon Kim
Jaehyeon Kim

Reputation: 3

Initializing pointer of itself through the function c++

This is a class, and one of the variables of the class is a pointer that points to an object made from the same class. I want to make a reference to a child object(new Point object), but when I call a function getChild() from the main function it throws access violation reading location exception. It seems that creating a new Point object is no problem, but the pointer (*child) goes back to null when the function is executed. How can I keep the pointer from pointing back to null?

class Point {
private:
    double x;
    double y;
    Point *child;
public:
    Point(double a, double b){
        x = a;
        y = b;
    }
    Point getChild() {
        return *child;
    }
    void createChild(double a, double b) {
        child = new Point(a, b);
    }
}

Upvotes: 0

Views: 110

Answers (1)

Stefan Riedel
Stefan Riedel

Reputation: 801

Your code has multiple problems:

Problem 1

You don't initialize child in the constructor, making every call to getChild before any call to createChild accessing "random" memory.

Problem 2

You're creating a copy every time you call getChild, which might not be what you want and which makes handling of your child pointer hard (because that gets copied too -> who owns the pointed-to object now?)

Problem 3

You don't check for nullptr in getChild

Problem 4

You don't delete your old child in createChild (and you don't delete it in your destructor)

Upvotes: 2

Related Questions