this pointer to base class constructor?
Posted
by Rolle
on Stack Overflow
See other posts from Stack Overflow
or by Rolle
Published on 2010-03-29T14:11:35Z
Indexed on
2010/03/29
14:13 UTC
Read the original article
Hit count: 137
c++
|class-design
I want to implement a derived class that should also implement an interface, that have a function that the base class can call. The following gives a warning as it is not safe to pass a this pointer to the base class constructor:
struct IInterface
{
void FuncToCall() = 0;
};
struct Base
{
Base(IInterface* inter) { m_inter = inter; }
void SomeFunc() { inter->FuncToCall(); }
IInterface* m_inter;
};
struct Derived : Base, IInterface
{
Derived() : Base(this) {}
FuncToCall() {}
};
What is the best way around this? I need to supply the interface as an argument to the base constructor, as it is not always the dervied class that is the interface; sometimes it may be a totally different class.
I could add a function to the base class, SetInterface(IInterface* inter), but I would like to avoid that.
© Stack Overflow or respective owner