开发者

Error while calling a virtual function

开发者 https://www.devze.com 2022-12-24 19:38 出处:网络
I have an error while calling a virtual function that is defined开发者_运维百科 in Derived class but not present in Base class? Why this error when I have pointer pointing to derived class?

I have an error while calling a virtual function that is defined开发者_运维百科 in Derived class but not present in Base class? Why this error when I have pointer pointing to derived class?

#include<iostream.h>

class A{
public:
virtual void fun()
{cout<<"A::fun()";
}
};

class B : public A
{
public:

virtual void fun()
{cout<<"B::fun()";
}
virtual void func()
{cout<<"B::func";
}
};

int main()
{
A *obj1=new B;
obj1->fun();
obj1->func();
}


This is the most un-friendly question I've seen yet on SO.

Of course you're getting the error (I'm guessing when you call obj1->func()) because your variable is a pointer to an object of type A, not B. So even though you've created a B, you're variable is acting like an A because the compiler has no idea it's actually a B saved in it.

You need to change your variable to point to a B: B* obj1 = new B;

Or you need to cast your pointer to B before you call func: ((B*)obj1)->func();


This is an error because although you at runtime have a pointer to a derived class, the compiler at compile time (when it emits the error message) doesn't know this - it just knows you have a pointer to the base class, and the base class doesn't have this function. So you have to declare the function as virtual in the base so that the compiler knows what you are talking about.

And BTW, its <iostream>, not <iostream.h>.

0

精彩评论

暂无评论...
验证码 换一张
取 消