Reputation: 33827
I have two classes:
class A {
int get();
string str();
}
string A::str() {
return string_with( get() );
}
class B : public A{
int get();
}
if I do:
A a
B b
b.str()
b
will invoke A::str()
(good) and it ill use A::get()
method (bad!). I want, that when I invoke b.str()
, the B::get()
is used by str
.
How to make it work?
Upvotes: 0
Views: 132
Reputation: 11
You can use virtual keyword. and then use pointer
class A
{
public:
virtual int get() { cout << "A::get()" << endl; return 0;}
string str()
{
cout << "A::str()" << endl;
get();
return "";
}
};
class B : public A
{
public:
virtual int get() { cout << "B::get()" << endl; return 0; }
};
B* b = new B; b->str();
the output: A::str() B::get()
Upvotes: 1
Reputation: 10490
In the magical word of Object-Oriented programming, there are two ways of calling a method: static and dynamic dispatch.
In static dispatch, the code called when you do something like a.do_it()
is determined statically, that is, it is determined upon the type of the variable a
.
In dynamic dispatch, the code called is determined dynamically, i.e., it is determined upon the type of the object referenced by a
.
C++, of course, supports both. How do you tell the compiler which type of dispatch do you want? Simple: by default you have static dispatch, unless you put the virtual
in the method declaration.
Upvotes: 2
Reputation: 77752
Just make it virtual. That's exactly what virtual is for.
Write
virtual int get();
in A's definition. And, just to make the code more understandable, do the same in B's.
By the way, I'm assuming that you meant to write class B : public A
.
Upvotes: 3