Search code examples
c++pointersdestructorfriend

Why is destructor called in Friend function


Why is Destructor Called in this Friend function show() C++? Also, how should the character pointer be initialized, it was set as 0... The full code with main is here https://justpaste.it/5x7fy

#include<iostream>
using namespace std;
#include<string.h>

class String
{

public:
    char *p;
    int len;
    String()
    {
        cout << "empty constructor" << endl;
        len=0;
        p=0;
    }
    // constructor
    String(const char *s) {
        len=strlen(s);
        p=new char[len+1];
        strcpy(p,s);
    }

    friend String operator+(const String&s, const String&t);
    friend int operator<=(const String&s, const String&t);
    friend void show(const String s);

    ~String() {delete p;}
};

void show(const String s)
{
    cout<<s.p<<endl;
}

Edit, read up on copy constructor and added one as:

// copy constructor
String(const String &s)
{
    len=s.len;
    p=new char[len+1]; // s.p;//
    strcpy(p,s.p);
}

The friend function parameter was passed by value before and the variable left the show function scope, therefore the destructor was called, now it is passed by reference.

    friend void show(const String & s);
...
    void show(String & s)
    {
        cout<<s.p<<endl;
    }

Edit updated the initialization of the character pointer in the empty constructor.

String() {
    p = new char[1]{'\0'};
    len = 1;
};

[latest source]: https://www.mediafire.com/file/31gb64j7h77x5bn/class38working.cc/file


Solution

  • The destructor is called because s is passed by value. That is, when you call show(something), that something is copied into s, which is later destroyed when execution of show ends.