-
question on polymorphism
ok..can anyone tell me more in detail what polymorphism is..all i know so far is that the base class and derive class has the same member functions name declare with virtual it gives it dynamic linkage..and kind of same with pointers....whats so good about ..please give examples..thanks
-
Ok... I will try :)
So imagine that you have this class
Code:
class Base
{
int x;
public:
Base (int xx=0): x(xx){}
virtual int getNum() {return x;};
void PrintNum( cout<<x;);
};
class Derivated
{
int newX;
public:
Derivated (int xx=1, int y=5): Base(xx){newX=y;}
int getNum() {return newX;}
void PrintNum() {cout<<NewX;}
};
void main()
{
Base num(5);
Derivated num2(5,10);
Base *ptr;
int y=num.getNum(); //just call the getNum from the base
cout<<y; //y=5
num.PrintNum(); //print 5
int w=num.getNum(); //Now it will call the getNum from the derivated classe because this function is virtual
cout<<w; //w=10
//Now came the nice part
ptr=new Derivated(5,20);
int z=ptr.getNum(); //it will call the getNum from the derivated
cout<<z; //z=20
ptr.printNum(); //it will print 5
}
i hope that i didn't say any stupid thing :). And i hope that you understand a bit more from classes...
-
your Derivated class didnt inherit any data members from the Base class
Code:
class Derivated
// should be
class Derivated: public Base
-
i fix your code
Code:
#include <iostream>
using namespace std;
class Base
{
int x;
public:
Base (int xx=0): x(xx){}
virtual int getNum() {return x;};
void PrintNum() { cout<<x; }
};
class Derivated: public Base
{
int newX;
public:
Derivated (int xx=1, int y=5): Base(xx){newX=y;}
int getNum() {return newX;}
void PrintNum() {cout<<newX;}
};
void main()
{
Base num(5);
Derivated num2(5,10);
Base *ptr;
int y=num.getNum(); //just call the getNum from the base
cout<<y; //y=5
num.PrintNum(); //print 5
int w=num.getNum(); //Now it will call the getNum from the derivated classe because this function is virtual
cout<<w; //w=10
//Now came the nice part
ptr=new Derivated(5,20);
int z=ptr->getNum(); //it will call the getNum from the derivated
cout<<z; //z=20
ptr->PrintNum(); //it will print 5
}
now it is syntax correct
-
also it should be num2.getNum() // outputs 10. but thanks i get what it does now.
if the derive class has the same member function name as the base class it will have static linkage which it will call the base class member function, but if you use virtual then it has dynamic linkage which then when you call through a pointer it will chose the object that is associated with it.
-
Of course
Sure it must be class Derivater:public Bse. Sorry... :)