Domanda

I have some codes like this:

#include <iostream>

using namespace std;
//base class
class Base
{
    public:
        Base(){}

        virtual void f()
        {
            cout<<"father.f()"<<endl;
        }
        virtual ~Base(){}
};
//a empty class
class Base1
{
    public:
        Base1(){}
        virtual ~Base1()
        {
            cout<<"~base1"<<endl;
        }
};
//the child class of the base class
class Child :public Base
{
    public:
        Child(){}
        virtual ~Child(){}
};
//the grandchild class of the base class,and child class of the base1 class
class Grand :public Base1,public Child
{
    public:
        Grand(){}
        virtual ~Grand(){}
        //overwrite base's f()
        void f()
        {
            cout<<"grand.f"<<endl;
        }
};
int main()
{
    void *v = new Grand();
    Base *b = (Base*)(v);
    //i think it print "father.f()",but it print"~base1"
    b->f();
    return 0;
}

I run these code in code::blocks(version13.12),but it print "~base1",I don't konw why it don't print "father.f()"。I think the v point to the address of the grand's virtual table,so when i convert v to base and invoke the f function,then b invoke the first virtual function in the virtual table.

I do not know i'm right or wrong,can u tell me.Thank all of!

Nessuna soluzione corretta

Altri suggerimenti

Because with multiple inheritance you can't cast directly to a upper class without passing by the child class. This because a void* doesn't contain any information about the layout in memory of the various classes that form your final Grand* instance.

To fix this you need indeed to cast it to it's runtime type:

Base *b = (Base*)(Grand*)v;
b->f();

Think about the fact that the layout could have Base in a different position. Think about another

class Grand2 : public Something, public Else, public Base1, public Child {
  ..
}

Now, where is Base located inside the Grand2 structure? In a different position compared to Grand. How could the compiler know the correct offset starting from just a pointer to a non specified class (which could be a Grand or a Grand2)?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top