Why my code does two instances, one for the parent class and one for the child class. I figure the code in the main() ask for only one. I try to unsterstand why that's happen, but no idea coming to my mind to solve this problem...
#include <iostream> class Mother { public: static int instance; Mother() { std::cout << "Mother constructor" << std::endl; instance++; } int get_instance() { return instance; } }; class Child : public Mother { public: Child() { std::cout << "Child constructor" << std::endl; this->instance++; } }; int Mother::instance = 0; int main() { Child child; std::cout << "instance: " << Mother::instance << std::endl; } console return
clang++ -std=c++11 -Wconversion *.cpp && ./a.out Mother constructor Child constructor instance<int>: 2
Childis aMother. You might want to think a bit more on whether or not this makes sense in the context of your program/example. See What is an example of the Liskov Substitution Principle? for more ways the OOP notion of inheritance is at odds with what you may expect.