Created
October 4, 2014 05:03
-
-
Save sergeant-wizard/89eb113840fd204f3d37 to your computer and use it in GitHub Desktop.
composition and inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SomeClass{ | |
public: | |
virtual void func() { | |
std::cout << "SomeClass::func called" << std::endl; | |
} | |
}; | |
class SubOfSomeClass : public SomeClass { | |
public: | |
virtual void func() override { | |
std::cout << "SubOfSomeClass::func called" << std::endl; | |
} | |
}; | |
class BadSuper { | |
public: | |
void init() { | |
someClass.func(); | |
} | |
protected: | |
SomeClass someClass; // bad idea if we expect SomeClass to be inherited | |
}; | |
class BadSub : public BadSuper { | |
public: | |
void someFunc() { | |
SubOfSomeClass* sosc = static_cast<SubOfSomeClass*>(&someClass); // down casting sucks | |
} | |
}; | |
class GoodSuper { | |
public: | |
void init() { | |
accessObject()->func(); // inherited classes of SomeClass will be called | |
} | |
protected: | |
virtual SomeClass* accessObject() { | |
return &someClass; | |
} | |
private: | |
SomeClass someClass; | |
}; | |
class GoodSub : public GoodSuper { | |
protected: | |
virtual SubOfSomeClass* accessObject() override { | |
return &sosc; | |
} | |
private: | |
SubOfSomeClass sosc; | |
}; | |
int main(void) { | |
GoodSub gs; | |
gs.init(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment