nahpr
nahpr

Reputation: 619

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.

Upvotes: 9

Views: 3172

Answers (2)

Code-Apprentice
Code-Apprentice

Reputation: 83537

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".

Upvotes: 2

aschepler
aschepler

Reputation: 72401

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

ptr->A::foo();

Upvotes: 19

Related Questions