Sorry if this is a beginner question, but I could not find an answer anywhere - I came across a class destructor in C++, in which there is
--num_strings;
I am wondering what the double dash means. Any help is appreciated, thanks. Below are parts of the header and cpp files:
// strngbad.h
#include <iostream>
class StringBad
{
private:
char * str;
int len;
static int num_strings;
public:
StringBad(const char * s);
StringBad();
~StringBad();
};
// strngbad.cpp
#include <cstring>
#include "strngbad.h"
using std::cout;
....
....
....
StringBad::StringBad(const char *s)
{
len = std::strlen(s);
str = new char[len + 1];
std::strcpy(str, s);
num_strings++;
}
StringBad::~StringBad()
{
--num_strings;
delete [] str;
}
Its the prefix decrement operator. It subtracts 1 from the variable and stores the result back in the variable. As an expression, it has the value of the result after the decrement. There's also a postfix decrement operator that behaves identically except the value of the expression is the variable value before the decrement.
(That's because num_strings is an int. Of course, like most operators in C++, if the variable is a class, it can define its own semantics for the prefix -- operator, so all bets are off as to what it does.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With