Reputation: 30276
I have this simple code:
class A {
public:
string toString() const { return "A"; }
};
class B : public A {
public:
string toString() const { // some code here }
};
I want toString()
in class B will inherit from class A and take some extra values. In this example, will be: "AB" (A: from class A, and B: extra string).
This is easy in Java, but I don't know how to do in C++. My first idea is take string from toString()
in class A and append additional string. So, to take this: I use: static_cast<A>(const_cast(this))->toString()
but it won't work :(
Please help me. Thanks :)
Upvotes: 0
Views: 337
Reputation:
First of all you probably want the toString to be virtual. Second, to accomplish what you want, you can do something like this in B::toString:
class B : public A
{
...
virtual string toString() const
{
string s = A::toString();
s += "B";
return s;
}
...
Upvotes: 1
Reputation: 15501
class A {
public:
string toString() const { return "A"; }
};
class B : public A {
public:
string toString() const { return A::toString() + "B"; }
};
In MS implementation (on Windows) you can do __super::toString() instead, but that's a non-portable MS extension.
Upvotes: 4
Reputation: 208333
string B::toString() const {
string result = A::toString(); // calls the member method in A
// on the current object
result += "B";
return result;
}
The qualification on the call to the function determines what function override (if the function is polymorphic) will be called, so it ensures that dynamic dispatch does not dispatch to B::toString()
again. The main difference from Java is that because C++ allows for multiple inheritance, you have to name the base A::
rather than just calling super
.
Upvotes: 2