Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 16000

Virtual Inheretance

$
0
0

The question is - why static_cast can cast upward from IOFile to File, but can't cast downward from File to IOFile:error: cannot convert from pointer to base class ‘File’ to pointer to derived class ‘IOFile’ because the base is virtual pe = static_cast<IOFile *>(pf). I think it is because for this conversion vtable is need to be used, so dynamic_cast will work. But why vtable is not used for upward conversion?

struct File {  int a;  File(int a) : a{a} {}  virtual ~File() {}};struct InputFile : virtual public File {  int b;  InputFile(int b) : File(b * 2), b{b} {}};struct OutputFile : virtual public File {  int c;  OutputFile(int c) : File(c * 3), c{c} {}};struct IOFile : public InputFile, public OutputFile {  int d;  IOFile(int d) : File(d), InputFile(d * 5), OutputFile(d * 7) {}};int main() {  IOFile *pe = new IOFile{11};  File *pf = static_cast<File *>(pe);  pe = static_cast<IOFile *>(pf);}

Viewing all articles
Browse latest Browse all 16000

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>