|
| Define a function with the same name and same number and type of parameters in the child class |
class parent
{
public:
int i1;
void f1()
{
i1 = i1 + 100;
cout << "parent method increases i1" << endl;
}
};
class child : public parent
{
public:
void f1()
{
i1 = i1 - 100;
cout << "child method DEcreases i1" << endl;
}
};
|
class parent
{
public:
int i1;
void f1()
{
i1 = i1 + 100;
cout << "parent method increases i1" << endl;
}
};
class child : public parent
{
public:
void f1()
{
i1 = i1 - 100;
cout << "child method DEcreases i1" << endl;
}
};
|
|
|
You will see that in
this case ,
the invocation:
|
class parent
{
public:
int i1;
virtual void f1()
{
i1 = i1 + 100;
cout << "parent method increases i1" << endl;
}
};
class child : public parent
{
public:
virtual void f1()
{
i1 = i1 - 100;
cout << "child method DEcreases i1" << endl;
}
};
|
|
|
You will see that in
this case ,
the invocation:
|
|
| Polymorphism is the ability to use one expression to convey multiple "meanings" (effects)/B> |
| Function polymorphism is the ability to one expression to invoke different functions (under different circumstances). |
class myOldClass
{
public:
int i1;
virtual void func1(int i)
{
i1 = i1 + i*i;
}
};
|
Consider now the expression:
myOldClass A; myNewClass B; myOldClass *ptr; ptr = &A; ptr->func1(4); // Invokes func1() in myOldClass ptr = &B; ptr->func1(4); // Invokes func1() in myNewClass |
Make sure you notice that:
|
myOldClass A; myNewClass B; myOldClass *ptr; ptr = &A; ptr->func1(); ptr = &B; ptr->func1(); |
Example:
void doSomething( myOldClass *ptr )
{
ptr->func1(4);
}
|
Consider now the expression:
myOldClass A; myNewClass B; doSomething( &A ); // Will invoke func1() in myOldClass doSomething( &B ); // Will invoke func1() in myNewClass |
Here, the assignment ptr = &A and ptr = &B is done through passing of parameters
Make sure you notice that:
|
Example:
void doSomething( myOldClass & x )
{
x.func1(4);
}
|
The function call will become:
myOldClass A; myNewClass B; doSomething( A ); // Will invoke func1() in myOldClass doSomething( B ); // Will invoke func1() in myNewClass |
Here, the reference &A and &B is done through passing of the parameter by reference
Example:
void doSomething( myOldClass x )
{
x.func1(4);
}
|
The compiler will use static binding in this case...
These function calls will both the function in myOldClass:
myOldClass A; myNewClass B; doSomething( A ); // Will invoke func1() in myOldClass doSomething( B ); // Will ALSO invoke func1() in myOldClass |
Vector Jacobi(Matrix P, Matrix Q, Vector b)
{
Vector v1, v2;
int i;
double d;
for (i = 0; i < 3; i = i + 1)
{ v1.x[i] = 0;
v2.x[i] = 1;
}
d = 0.1;
while ( d > 0.0001 )
{
v2 = P*v1 + Q*b;
d = distance(v1, v2);
v1 = v2;
}
return(v2);
}
|
DenseMatrix P1, Q1; Vector sol, b; sol = Jacobi( P1, Q1, b); |
SparseMatrix P1, Q1; Vector sol, b; sol = Jacobi( P1, Q1, b); |
Nothing else need to be changed !!!