Reputation: 53
I apologize for the nooby question, but I've just started programming in obj-oriented paradigm.
I have a function that takes a pointer to a class void foo(myClass* C)
and this class has its own method
class myClass{
public:
double fooMethod();
/* ... */
}
Now I would like to pass to foo
an object with an overloaded method fooMethod
so I thought about creating a derived class
class myDerivedClass : public myClass{
public:
double fooMethod(); // overloaded method
/* ... */
}
The problem is that if I instantiate an object myDerivedClass* D = new myDerivedClass
and pass it foo(D)
, this function will use the method of the base class, i.e., myClass::fooMethod()
and instead I would like it to use myDerivedClass::fooMethod()
.
How do I make this happen? I have this problem since I don't want to re-write already working code, like foo
or myClass
, but I would like to adapt my new features to the current structure of the code.
Thank you very much! L.
Upvotes: 0
Views: 280
Reputation: 7625
You can do like this
class myClass{
public:
virtual double fooMethod();
/* ... */
}
class myDerivedClass : public myClass{
public:
double fooMethod() override; // override method, not overload
/* ... */
}
Then if you pass a myDerivedClass
object pointer/reference, and use it to call fooMethod()
, the overriden
method in myDerivedClass
will be called.
The concept is you can override base class method, not overload.
Upvotes: 1
Reputation: 6069
In object-oriented programming in order to derived class' method be executed when you call base class' method you need that method to be virtual
. In some languages like Java all methods by default are virtual, but in C++ you have to manually add keyword virtual
in method definition in base class, like this:
class myClass{
public:
virtual double fooMethod();
/* ... */
}
Upvotes: 1