The following code is to verify if I have a pointer member in a class, without making an overloaded assignment operator. When I make two instances equal,it will just make the pointers point to the same thing instead of copying the data. However, I got an error trying to compile before I could verify. It appears to me that it implies a pointer member in class has to be pointed to a heap-allocated data. Is it right?
The error is: initializing pointer member 'a' with the stack address of parameter 'aa' [-Werror,-Wdangling-field]
Second question is when do we need an overloaded "="operator? I guess would be when we have a pointer member in the class and we want whatever the pointer points to to be copied again instead of just making two pointer from the two classes point to same thing. Could somebody tell me this is correct. Thanks!
class ClassA {
int* a;
int* b;
ClassA():a(NULL),b(NULL){};
ClassA(int aa,int bb):a(&aa),b(&bb){};
};
int main(){
ClassA test;
ClassA subject(5,6);
test = subject;
}