Zed
Zed

Reputation: 115

multiple inheritance cast in c++

I have an issue concerning multiple inheritance cast. I have 3 base classes

class ReadFile;
class WriteFile
class SharedObject; // this class is basically a mutex

based on those class I build:

class ReadWriteFile : public ReadFile, public WriteFile
{ ... };

class ReadWriteSharedFile : public ReadWriteFile , public SharedObject
{ ... };

class ReadFileShared : public ReadFile, public SharedObject
{ ... };

at some point of my code, I have a ReadWriteSharedFile pointer that I would like to cast as a pointer to a ReadFileShared

ReadFileShared * l_data = dynamic_cast<ReadFileShared * >(m_data); // m_data is a ReadWriteSharedFile 

it compiles but at execution, the cast "fails" and l_data is NULL

However, what I want to achieve sounds legit to me. Is it? What am I doing wrong. Thanks

Upvotes: 1

Views: 325

Answers (2)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136256

ReadFileShared and ReadWriteSharedFile are unrelated classes, although they inherit some same base classes. Therefore, you cannot cast a reference/pointer to one to another.

Your functions should probably use interfaces ReadFile and WriteFile, rather than require a particular implementation of them. That is the main idea behind interfaces. See C++ Interface Classes - An Introduction for more details.

Upvotes: 7

Artak Begnazaryan
Artak Begnazaryan

Reputation: 469

dynamic_cast<> is used to upcast the derived class pointer to one of its primarily ascendant classes. In your case ReadWriteShared class is not derived from ReadFileShared so dynamic_cast<> will return null pointer.

Upvotes: 1

Related Questions