Skip to content

Instantly share code, notes, and snippets.

@sergeant-wizard
Created October 4, 2014 05:03
Show Gist options
  • Save sergeant-wizard/89eb113840fd204f3d37 to your computer and use it in GitHub Desktop.
Save sergeant-wizard/89eb113840fd204f3d37 to your computer and use it in GitHub Desktop.
composition and inheritance
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