V
V
Vladimir Korshunov2021-10-02 00:23:37
C++ / C#
Vladimir Korshunov, 2021-10-02 00:23:37

Why is the class constructor not called?

There is such a real number class with two constructors:

class R
{
private:
    double value;
public:
    //конструктор
    R(double a) : value(a) {};
    R() : value(0) {};
    //Геттер
    double get_number() {return value;};
    //Сеттер
    void set_number(double a) {value = a;};
};

There is such a queue class:
class Queue
{
private:
    struct elem
    {
        elem *next, *prev;
        R info;
    };
    elem *head, *tail;
    int len;
public:
    //конструктор
    Queue(double inf)
    {
        head = new elem;
        tail = new elem;
        len = 1;
        head->info.set_number(inf);
    };
    Queue()
    {
        head = NULL;
        tail = NULL;
        len = 0;
        head->info.set_number(0);
    }
...

If I create such an object:
a.dequeue();
The head->info.set_number(0); line is executed, after which the R class constructor is NOT called, the setter is called, and then a memory error pops up. Why is that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2021-10-02
@GashhLab

You somehow misunderstand C++.
You have written:


Queue()
{
head = NULL;
tail = NULL;
len = 0;
head->info.set_number(0);
}

head =
ANYWHERE ANYWHERE -> info.set_number(0);
Naturally, turning to ANYWHERE leads to undefined behavior of the program, which is expressed in a crash.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question