class Derive:public Base
{
private:
{
.....
}
public:
void show
{
cout<<" i m derive class...";
}
};
void main()
{
derive d;
d.show;
getch();
}
my question is why we can't directly call the member function of the desired class instead of using virtual function.
pls explain it..
***********same program using virtual keyword*******************
class Base
{
private:
{
.....
}
public
{
virtual void show()
{
cout<<"i m base class ..";
}
};//end of Base class
class Derive:public Base
{
private:
{
.....
}
public:
void show
{
cout<<"i m derived class...";
}
};
void main()
{
Base *b;
Derived obj;
b=&obj;
b->show();//i hope it invoke show() function of derive class
getch();
}
Why we generally prefer the 2nd one i.e with virtual keyword..
why we can't directly call the member function of the desired class instead of using virtual function...make me understand this point..
do you understand basic inheritance? do you understand the basics of run time polymorphism?, you're asking about aggregation. learn about is-a relationship and has-a relationship you will find out the difference. don't take my post the wrong way this is not a harsh tone. instead of asking this kind question, learn about the subject. seems to me all you learned was the syntax, and that was wrong as well. before you learn the syntax, you need to have a strong understanding for the subject.
Image a situation where you know that a Base or one of its derivatives will be created, but you don't know which one. For instance, a message might come from a remote device, or a user might pick an unspecified shape from a palette to display. At that point, you know you might have a Derive or a Base, or maybe one of 50 other derived objects to choose from. By using virtual functions in the Base class, you can make sure the proper functionality is called on any specific object.
#include <iostream>
#include <list>
usingnamespace std;
class Base
{
private:
public:
virtualvoid show() { cout<<"i m base class .." << endl; }
};//end of Base class
class Derive:public Base
{
private:
public:
void show() { cout<<"i m derived class..." << endl; }
};
class Derive2:public Base
{
private:
public:
void show() { cout<<"i m derived class #2..." << endl; }
};
int main()
{
// Create the objects
list<Base*> myList;
myList.push_back(new Base);
myList.push_back(new Derive);
myList.push_back(new Derive2);
// Show the objects
for (list<Base*>::iterator it = myList.begin(); it != myList.end(); it++)
{
Base* ptr = *it;
ptr->show();
}
cin.get();
return 0;
}
Arbitrary objects are created in lines 30-32. In line 38 the show() function is called on all of the objects without having to cast anything to a derived type.
Try this code without the "virtual" keyword, and all of the classes will use the Base function.