I was asked this crazy question. I was out of my wits.
Can a method in base class which is declared as virtual be called using the base class pointer which is pointing to a derived class object?
Is this possible?
I was asked this crazy question. I was out of my wits.
Can a method in base class which is declared as virtual be called using the base class pointer which is pointing to a derived class object?
Is this possible?
If you're trying to invoke a virtual method from the base class pointer, yes.
That's polymorphism.
If you're asking, with a base class pointer to a derived class, can you invoke a base class method that is overriden by the derived class? Yes that's also possible by explicitly scoping the base class name:
basePtr->BaseClass::myMethod();
You mean something like this. (Where pBase
is of type pointer-to-base but the pointed-to object is actually of type Derived
which is derived from Base
.)
pBase->Base::method();
Yes, it's possible.
Try:
class A { virtual void foo(); }
class B : public A { virtual void foo(); }
A *b = new B();
b->A::foo ();
No. Not in a clean way. But yes. You have to do some pointer manipulation, obtain a pointer to the vtable and make a call. but that is not exactly a pointer to base class, but some smart pointer manipulation. Another approach is using scope resolution operator on base class.
Yes -- you have to specify the full name though:
#include <iostream>
struct base {
virtual void print() { std::cout << "Base"; }
};
struct derived : base {
virtual void print() { std::cout << "Derived"; }
};
int main() {
base *b = new derived;
b->base::print();
delete b;
return 0;
}
If I understand the question correctly, you have
class B
{
public:
virtual void foo();
};
class D: public B
{
public:
virtual void foo();
}
B* b = new D;
And the question is, can you call B::foo()
. The answer is yes, using
b->B::foo()
class B
{
public:
virtual void foo();
};
class D: public B
{
public:
virtual void foo();
}
B* b = new D;
Try calling
(*b).foo()
to invoke base class foo function