Inheritance: SubClass extends SuperClass
Today I had a go at inheritance in C++ I get the general idea, but the compiler still throws a lot of errors at me.
[code language="cpp"]
#include <string>
#include <iostream>
using namespace std;
class SuperString {
protected: string class_s;
public:
SuperString(string in_s): class_s(in_s) {}
virtual string get_loud(){
return class_s + "!";
}
};
class SubString: public SuperString {
public:
SubString(string in_s): SuperString(in_s) {}
string get_loud() {
return SuperString::class_s + "!!";
}
};
int main () {
SuperString s_instance(" Pow");
SubString sub_instance(" Pow");
cout << s_instance.get_loud() << sub_instance.get_loud() << endl;
}
[/code]
I also though I'd need the override keyword in substring::get_loud(), but I actually had to remove it. So yes, my code will compile, but I'm not confided that the above code is OK by any standard. For instance, the book uses "const" a lot. I guess ought to know why instead of just ... not using it.
From the book:
[code language="cpp"]
// in super:
virtual string get() const { // codeblock }
// in sub:
void get() const override {// codeblock }
[/code]
Maybe chapter 15.3 can tell me why.
Etiketter: c++

0 Kommentarer:
Legg inn en kommentar
Abonner på Legg inn kommentarer [Atom]
<< Startsiden