NOTE : -
THIS CONTENT IS NOT ORIGINAL
27. If a method is declared virtual the program will always check the type of the instance that is pointed to and will use the appropriate method
In the program above, r->module() calculates the vector module, using x and y, because r has been declared a vector pointer. The fact that r actually points to a trivector is not taken into account. If you want the program to check the type of the pointed object and choose the appropriate method, then you must declare that method as virtual inside the base class.
(If at least one of the methods of the base class is virtual then a "header" of 4 bytes is added to every instance of the classes. This allows the program to determine what a vector actually points to.) (4 bytes is probably implementation specific. On a 64 bit machine maybe it is 8 bytes...)
In the program above, r->module() calculates the vector module, using x and y, because r has been declared a vector pointer. The fact that r actually points to a trivector is not taken into account. If you want the program to check the type of the pointed object and choose the appropriate method, then you must declare that method as virtual inside the base class.
(If at least one of the methods of the base class is virtual then a "header" of 4 bytes is added to every instance of the classes. This allows the program to determine what a vector actually points to.) (4 bytes is probably implementation specific. On a 64 bit machine maybe it is 8 bytes...)
using namespace std;
#include
#include
class vector
{
public:
double x;
double y;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
virtual double module()
{
return sqrt (x*x + y*y);
}
};
class trivector: public vector
{
public:
double z;
trivector (double m = 0, double n = 0, double p = 0)
{
x = m; // Just for the game,
y = n; // here I do not call the vector
z = p; // constructor and I make the
} // trivector constructor do the
// whole job. Same result.
double module ()
{
return sqrt (x*x + y*y + z*z);
}
};
void test (vector &k)
{
cout << "Test result: " << k.module() << endl;
}
int main ()
{
vector a (4, 5);
trivector b (1, 2, 3);
cout << "a (4, 5) b (1, 2, 3)" << endl << endl;
vector *r;
r = &a;
cout << "module of vector a: " <<>module() << endl;
r = &b;
cout << "module of trivector b: " <<>module() << endl;
test (a);
test (b);
vector &s = b;
cout << "module of trivector b: " << s.module() << endl;
return 0;
}
| Output |
| a (4, 5) b (1, 2, 3) module of vector a: 6.40312 module of trivector b: 3.74166 Test result: 6.40312 Test result: 3.74166 module of trivector b: 3.74166 |
BIBILOGRAPHY / REFERENCE : - http://www.4p8.com/eric.brasseur/cppcen.html

No comments:
Post a Comment