I've created a class and a derived class that are almost completely the same. The only difference is that the derived class has 2 different functions and 3 extra variables. I want the called function from class B to use the inherited function but with the PrivFunctions of class B. Instead when called, the function uses the PrivFunctions of his own class, class A.
class A
{
protected:
double x,y,z;
Function() {
*do something using the member variables of class A and the member functions of class A* }
private:
double PrivFunction() {
*take in member variables from A and return a certain value* }
double PrivFunction2() {
*take in member variables from A and return a certain value* }
class B : public A
{
private:
double a,b,c;
double PrivFunction() {
*take in member variables from A,B and return a certain value* }
double PrivFunction2() {
*take in member variables from A,B and return a certain value* }
main() {
B classb();
B.Function()
}
I've thought about adding the addresses of the private functions in the Function() but that seems too far fetched. I feel like I'm missing something simple but I just can't find out how to do this neatly
What you need to do is declare the function in the base class as virtual
. This is a type of function that you define in the base class A
, and then need to redefine in the sub-classes. Declaring functions as virtual
ensures that the correct functions are being called and avoids ambiguity.
You code should look something like this:
class A
{
protected:
double x, y, z;
//define as virtual
virtual Function(){/*do something*/}
/*
rest of your code
*/
}
class B: public A
{
private:
double a, b, c
public:
//redefine your function in the subclass
Function(){/*do something else*/}
/*
rest of your code
*/
}
int main()
{
B classb();
//This will now use B's Function
classb.Function();
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments