Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: How to call a parent class function from outside

I have:

class A{
    public:
        virtual void foo();
};

class B : public A{
    public:
        void foo();
};

B *ptr = new B();

I want to call A's foo() DIRECTLY using the 'ptr' pointer.

When I try

(A*)ptr->foo();

it still calls B's version of foo(). How do I call A's version instead?

Is this possible? What are the alternatives? Thank you.

like image 289
nahpr Avatar asked Aug 29 '12 16:08

nahpr


2 Answers

When you name a function with the :: scope-resolution form, you call the named function, as though it were not virtual.

ptr->A::foo();
like image 137
aschepler Avatar answered Oct 18 '22 18:10

aschepler


You need to make your functions public. You do this simply by making the following change:

class A{
    public:
        virtual void foo();
};

class B : public A{
    public:
        void foo();
};

When you don't do this, the functions are automatically private and inaccessible from the "outside".

like image 30
Code-Apprentice Avatar answered Oct 18 '22 16:10

Code-Apprentice