Hugo R
Hugo R

Reputation: 25

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

Upvotes: 1

Views: 315

Answers (2)

user13349869
user13349869

Reputation: 1

Your friend function show takes the String parameter per value, which means that whatever argument is passed to the function, a local copy is created and used inside the function. Of course, this local copy is destroyed - again when the show() function ends.

If you pass the string by reference (const string**&** s), you won't get an extra temp copy nor any destruction of that.

Upvotes: 0

numzero
numzero

Reputation: 2057

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.

Upvotes: 4

Related Questions