D
Daniel Aarno
Consider the following code:
typedef int A;
class B {
public:
B(A& var) : m_var(var) {}
virtual ~B() {}
protected:
A &m_var;
};
class C : public B {
public:
C(A* a) : B(*a) {}
~C();
};
int main()
{
A* a = new A();
C c(a);
}
I now want to implement the destructor of C to deallocate a (which is
referenced through A::m_var).
I tried this code:
C::~C()
{
delete &B::m_var;
}
which gave me the following error
tst.cc: In destructor `virtual C::~C()':
tst.cc:9: error: `A&B::m_var' is protected
tst.cc:26: error: within this context
tst.cc:26: error: cannot create pointer to reference member `B::m_var'
Hmmm, that was strange, I have "always" gotten pointer to member references...
so I tried the follwing:
C::~C()
{
A& tmp = B::m_var;
delete &tmp;
}
which worked fine. Just to make sure I also tried
C::~C()
{
A* tmp = &B::m_var;
delete tmp;
}
which (as I now expected) gave me a similar error to the one above.
Finnaly I settled for the implementation shown below which also worked fine,
i.e. I removed the scoping to B.
C::~C()
{
delete &m_var;
}
Can anyone please elaborate exactly what is the correct way to go here and why
one works and not the other, they all seem to be the same thing to me but
probably I'm missing out on some details here.
/Daniel Aarno
typedef int A;
class B {
public:
B(A& var) : m_var(var) {}
virtual ~B() {}
protected:
A &m_var;
};
class C : public B {
public:
C(A* a) : B(*a) {}
~C();
};
int main()
{
A* a = new A();
C c(a);
}
I now want to implement the destructor of C to deallocate a (which is
referenced through A::m_var).
I tried this code:
C::~C()
{
delete &B::m_var;
}
which gave me the following error
tst.cc: In destructor `virtual C::~C()':
tst.cc:9: error: `A&B::m_var' is protected
tst.cc:26: error: within this context
tst.cc:26: error: cannot create pointer to reference member `B::m_var'
Hmmm, that was strange, I have "always" gotten pointer to member references...
so I tried the follwing:
C::~C()
{
A& tmp = B::m_var;
delete &tmp;
}
which worked fine. Just to make sure I also tried
C::~C()
{
A* tmp = &B::m_var;
delete tmp;
}
which (as I now expected) gave me a similar error to the one above.
Finnaly I settled for the implementation shown below which also worked fine,
i.e. I removed the scoping to B.
C::~C()
{
delete &m_var;
}
Can anyone please elaborate exactly what is the correct way to go here and why
one works and not the other, they all seem to be the same thing to me but
probably I'm missing out on some details here.
/Daniel Aarno