Reputation: 39
I know this
// C++ program for function overriding
#include <bits/stdc++.h>
using namespace std;
class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};
class derived:public base
{
public:
void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly
{ cout<< "print derived class" <<endl; }
void show ()
{ cout<< "show derived class" <<endl; }
};
//main function
int main()
{
base *bptr;
derived d;
bptr = &d;
//virtual function, binded at runtime (Runtime polymorphism)
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
return 0;
}
I can get printed
print derived class
show base class
show derived class
can I print
print base class
with the object d
of the derived class with just changing main()
and without creating another object? if yes how?
Upvotes: 2
Views: 147
Reputation: 206737
can I print print base class with the object
d
of the derived class with just changingmain()
Yes, you can. You have to explicitly use the base class in the call.
bptr->base::print();
You can also use d
directly.
d.base::print();
Upvotes: 11