0

I need some clarification about Structs as Bases of a Derived Object. . The current code I'm maintaining ( Legacy , VS2008 ) had classes with Struct as their bases, and being used like this.

struct Base 
{
 int nSomeValue;
 Base(int m_SomeValue): nSomeValue(m_SomeValue){};
};
class Derived : public Base
{
Derived (int m_OtherValue,int m_SomeOtherValue)
: nOtherValue(m_OtherValue),nSomeOtherValue(m_SomeOtherValue){};
~Derived(){};
public:
int nOtherValue;
int nSomeOtherValue
};


int main()
{
  Derived* pDerived = new Derived(10,20);
  std::cout<<"Derived Object's Value is " << pDerived->nOtherValue << " and " << pDerived->nSomeOtherValue << std::endl;
  delete pDerived;
  pDerived = NULL;
}

I noticed that some of the Structs had virtual Destructors in them like this.

struct Base 
{
 Base(int m_SomeValue): nSomeValue(m_SomeValue){};
 virtual ~Base(){};
 int nSomeValue;
};

My questions is as follows

#1. Should structs have virtual Destructors let alone a destructor at all?

#2. Is it safe to assume that when a Struct is used as a base without a destructor that the memory allocated for it would be freed when delete is used on the Derived Object?

  • 2
    There are exactly two differences between a `struct` and a `class` in C++. First, in a struct, the default is that members are public; in a class the default is private. Second, when a struct is a derived type, it’s base is, by default, public; with a class the default is private. In both cases, an explicit access specifier, of course, controls. Other than that, anything you’d do with a class works the same with a struct. – Pete Becker Apr 18 '22 at 23:31
  • @PeteBecker thank you for the clarification I was very confused due to this thread https://stackoverflow.com/questions/8276036/why-structs-cannot-have-destructors, I know that it's C# specific but someone also described the Behavior of C++ , that specifically said that one shouldn't include the destructor in a Struct. So Was I correct to assume that if a Struct is used as a Base of a class it to should have a virtual destructor to properly de-allocate an object? – Azriel Elijay Apr 19 '22 at 00:19
  • There’s nothing special about being a struct. If it needs a destructor write a destructor. If it needs a virtual destructor write a virtual destructor. – Pete Becker Apr 19 '22 at 00:52

0 Answers0