I am trying to make a class like string(for learning purposes) and i have the following files
var.cpp:
#include "var.hpp"
var::var(){}
var::var(const char* v) {
    (*this) = v;
}
var var::operator=(const char*& v) {
    if(string_var) {
        free((void*)string_var);
        string_var = NULL;
    }
    if(!v) return (*this);
    string_var = strdup(v);
    return (*this);
}
var::~var() {
    if(string_var && *string_var) free((void*)string_var);
}
var.hpp:
#include <iostream>
#include <cstring>
#include <cstdlib>
class var {
private:
    const char* string_var = NULL;
public:
    var();
    var(const char* v);
    var operator=(const char*&);
    ~var();
};
test.cpp:
#include "var.hpp"
int main() {
    var v1 = "test";
}
it compiles without any errors.
with gdb i ran the compiled program and i found that when it goes from the constructor to the operator=, the operator= does its job correctly but when it returns i check the this(like: p *this) and the string_var is "".
I am still learning so please help me understand why and how to fix it.
EDIT
After some debugging i found that the destructor gets called inside the constructor; at least that's what i understand from the following output:
Breakpoint 1, var::~var (this=0x7fffffffde60, __in_chrg=<optimized out>) at var.cpp:21
21  var::~var() {
(gdb) back
#0  var::~var (this=0x7fffffffde60, __in_chrg=<optimized out>) at var.cpp:21
#1  0x00005555555552ef in var::var (this=0x7fffffffde80, v=0x555555556005 "ok") at var.cpp:7
#2  0x00005555555551f7 in main () at test.cpp:5
 
     
    