Please Help with overriding a string return type

How can I override tostring() function? I want to say when sub class fail to override then parent class display invalid. I am not sure about below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//card class header
class Card{
public:
string toString();
};

//card.cpp
string Card::toString(){
return string("Not defined in sub class");
}

//turn class header
class Turn: public Card{
public:
string toString();
};

//turn.cpp
string Turn::toString(){
string str("You turn to ");
std::stringstream ss;
ss << turnto;
str.append(ss.str());
return str;
}

Last edited on
1
2
3
4
5
//card class header
class Card{
public:
virtual string toString(); // <-- mark the parent class member as virtual.
};
I am following a class diagram. In it toString is not virtual in the card class.
Did you try it?
That is what virtual is for, it specifies that a sub class may overwrite it else it will use the default.
A pure virtual function specifies a subclass must overwrite it and it is declared like this:

1
2
3
4
5
6
//card class header
class Card{
public:
virtual string toString() = 0;
};


Notice the = 0; // <-- pure virtual

Regardless of what your class diagram tells you, this is how it is done.
And I would speculate that this is the reason you haven't been able to do it.
Else you wouldn't be here asking.

1
2
3
4
5
//turn class header
class Turn: public Card{
public:
string toString();
};


the turn class will also need a default constructor at least;
Last edited on
Thanks CodeGoggles. I understand it now. Using virtual, a sub class may overwrite it else it will use the default and when using pure virtual a subclass must overwrite it. I have only included some parts of the code.
Glad to have helped. Please mark thread solved if you are happy with the responses.
Topic archived. No new replies allowed.