views:

147

answers:

2

In the C++ program:

              #include<iostream.h>
              class A
              {
                     public: virtual void func()=0;
              };
              class B:public A
              {
                     public: void show()
                             {
                                   func();
                             }
              };
              void B::func()
              {
                      cout<<"In B"<<endl;
              }
              int main()
              {
                   B b;
                   b.show();
              }

If the virtual function, func() is redefined within body of the class B, there is no error. But when using the scope resolution operator, the compiler throws an error. Why is that?

+12  A: 

This is not directly related to func being virtual, you always need to declare it in the class:

class B:public A
{
   public: void show()
   {
      func();
   }

   void func();  // add this
};

void B::func()
{
   cout<<"In B"<<endl;
}
Henk Holterman
Otherwise it will not know that B defines func and will try to use the pure virtual version in A, which it can't because it is pure virtual
Xetius
@Xetius: Please; if you don't know please try and compile test code first before answering. If there is no 'func' defined in B. Then show() will use the version in A. Which is absolutely fine. Because at run-time it will call the most derived version belonging to the current instance. If B does not define 'func' then it is an abstract class and you will just will not be able to instantiate an instance of B.
Martin York
+4  A: 

You have to declare that you redefine the member function func() in class B.

class B:public A
{
   virtual void func();
public:
   void show() {func(); }
};
Didier Trosset