-3

I have an example code snippet:

class A
{
public:
    virtual void func1();
    virtual void func2();
};
class B
{
public:
    virtual void func2();
    virtual void func3();
};

void main()
{
    A *obj = new B;
    obj->func3();  
}

Why does the line obj->func3(); return error?
(we know that a separate virtual table is created for each class)"

Deduplicator
  • 44,692
  • 7
  • 66
  • 118

3 Answers3

2

Because obj is a pointer to A. A doesn't have func3 on it, so you can't call it.

Note: I've assumed you actually wanted to inherit B from A - it would error before the call, on the assignment in current state.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
2

There's no way this could possibly work. Consider:

Class B : public A
{
    void Foo (int);
};

class C : public A
{
    void Foo (char);
};

class D : public A
{
    void Foo (double);
}

void bar (A* obj)
{
   obj->Foo (1); // Uh oh!
}

How can the compiler know what code to generate? Should this pass an integer? A float? A character?

And it's never safe, because the compiler is not able to see the definitions of all the derived classes when it's compiling functions like bar.

If you want to call a function through pointers to a base class, the base class needs to at least define what parameters that function takes.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

Your code should look like this if it needs to work. You need to declare the function in base class otherwise in vtable for func3() it space will not be alloted in base class.

class A
{
public:
virtual void func1();
virtual void func2();
virtual void func3();  //virtual function , linking at run time depends on what object it points to 
};
class B : public A   //public inheritance
{
public:
virtual void func2();
virtual void func3(); 
};

void main()
{
A *obj = new B;  //base class pointer pointing to derived class object
obj->func3();  //since func3() is declared as virtual  , dynamic linking takes place and since at 
                // run times it points to object b , function in class B is invoked
}
evk1206
  • 433
  • 7
  • 18