Search code examples
c++inheritancevirtual

C++ Virtual function implementation?


If I have in C++:

class A {
    private: virtual int myfunction(void) {return 1;}
}

class B: public A {
    private: virtual int myfunction(void) {return 2;}
}

Then if I remove virtual from the myfunction definition in class B, does that mean that if I had a class C based on class B, that I couldn't override the myfunction since it would be statically compiled?

Also, I'm confused as to what happens when you switch around public, and private here. If I change the definition of myfunction in class B to be public (and the one in class A remains private), is this some sort of grave error that I shouldn't do? I think that virtual functions need to keep the same type so that's illegal, but please let know if that's wrong.

Thanks!


Solution

  • The first definition with 'virtual' is the one that matters. That function from base is from then on virtual when derived from, which means you don't need 'virtual' for reimplemented virtual function calls. If a function signature in a base class is not virtual, but virtual in the derived classes, then the base class does not have polymorphic behaviour.

    class Base
    {
        public:
        void func(void){ printf("foo\n"); }
    };
    class Derived1 : public Base
    {
        public:
        virtual void func(){ printf("bar\n"); }
    };
    class Derived2 : public Derived1
    {
        public:
        /*  reimplement func(), no need for 'virtual' keyword
            because Derived1::func is already virtual */
        void func(){ printf("baz\n"); } 
    };
    
    int main()
    {
        Base* b = new Derived1;
        Derived1* d = new Derived2;
    
        b->func(); //prints foo - not polymorphic
        d->func(); //prints baz - polymorphic
    }