Jules
Jules

Reputation: 134

Class instatiation using pointers

Could someone shed some light on how the next piece of code works on the creation of the object b?? It looks like it is working with a default copy constructor?. I don't see how it is working with an object that has never been instantiated, object v.

#include <iostream>
using namespace std;
class A {
public:
    A(float v) { A::v = v; cout << "hola" << endl;}
    float v;
    float set(float v) {
        A::v = v;
        return v;
    }
    float get(float v) {
        return A::v;
    }
};
int main() {
    A c(2.0);
    A *v;
    A *a = new A(1.0), *b = new A(*v);
    cout << a->get(b->set(c.v));
    return 0;
}

Upvotes: 0

Views: 84

Answers (1)

No. We can't shed any light on how it works. v has never been initialized, so trying to copy from the object it (doesn't) point at is undefined behaviour. Trying to reason about undefined behaviour is an exercise in futility except for debugging purposes. The most likely behaviour is either a seg-fault, or *b will be a copy of some random piece of memory.

As Peter points out in his comment the compiler is not required to diagnose instances of undefined behaviour. In this case, I would expect most compilers to warn if you crank up the warning level (-Wall -werror are good flags to use).

Upvotes: 3

Related Questions